Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
703 views
in Technique[技术] by (71.8m points)

html - Table columns, setting both min and max width with css

I would like to have a table which in the columns can stretch but I'm having a little trouble with min and max width in css.

It also seems that theres some conflicting answers around how this works:

I would like to have the following

table{
   width:100%;
}
.a, .b, .c
{
    background-color: red;
}
.a
{
    min-width: 10px;
    max-width: 20px;
}
.b
{
    min-width: 40px;
    max-width: 45px;
}
.c
{
}

<table>
    <tr>
        <td class="a">A</td>
        <td class="b">B</td>
        <td class="c">C</td>
    </tr>
</table>

Is there a way of achieving this without javascript (ie constrained stretching of columns with a table)?

below is a table of what actually gets rendered for some different css setups:

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Tables work differently; sometimes counter-intuitively.

The solution is to use width on the table cells instead of max-width.

Although it may sound like in that case the cells won't shrink below the given width, they will actually.
with no restrictions on c, if you give the table a width of 70px, the widths of a, b and c will come out as 16, 42 and 12 pixels, respectively.
With a table width of 400 pixels, they behave like you say you expect in your grid above.
Only when you try to give the table too small a size (smaller than a.min+b.min+the content of C) will it fail: then the table itself will be wider than specified.

I made a snippet based on your fiddle, in which I removed all the borders and paddings and border-spacing, so you can measure the widths more accurately.

table {
  width: 70px;
}

table, tbody, tr, td {
  margin: 0;
  padding: 0;
  border: 0;
  border-spacing: 0;
}

.a, .c {
  background-color: red;
}

.b {
  background-color: #F77;
}

.a {
  min-width: 10px;
  width: 20px;
  max-width: 20px;
}

.b {
  min-width: 40px;
  width: 45px;
  max-width: 45px;
}

.c {}
<table>
  <tr>
    <td class="a">A</td>
    <td class="b">B</td>
    <td class="c">C</td>
  </tr>
</table>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...