Luke McGregor Luke McGregor - 1 year ago 60
CSS Question

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

.a, .b, .c
background-color: red;
min-width: 10px;
max-width: 20px;
min-width: 40px;
max-width: 45px;

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

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

Answer Source

Tables work differently; sometimes contra-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 new fiddle, in which I removed all the borders and paddings and border-spacing, so you can measure the widths more accurately.