Marc Becker Marc Becker - 2 months ago 32
CSS Question

using calc() with tables

I'm trying to get a table with fixed-width

td
s and variable-width
td
s.

Im using the CSS
calc()
function, but somehow it seems like I can't use
%
in tables.

So that is what I have so far:

<table border="0" style="width:100%;border-collapse:collapse;">
<tr style="width:100%">
<td style="width:30px;">1</td> <!--Fixed width-->
<td style="width: calc( (100% - 230px) / 100 * 40);">Title</td> <!--Width should be 40% of the remaining space-->
<td style="width: calc( (100% - 230px) / 100 * 40);">Interpret</td> <!--Width should be 40% of the remaining space-->
<td style="width: calc( (100% - 230px) / 100 * 20);">Album</td> <!--Width should be 20% of the remaining space-->
<td style="width:80px;">Year</td><!--Fixed width-->
<td style="width:180px;">YouTube</td><!--Fixed width-->
</tr>
</table>


How I see it, it should work, but it isn't.

Does anybody know how to solve this? Or maybe has an other suggestion how I could reach my goal?

Answer

Tables have difficult rules about distributing the space of the columns because they distribute space dependent on the content of the cells by default. Calc (atm) just wont work with that.

What you can do however is to set the table-layout attribute, set a width (100% works), and ensure it is display: table to force the td elements to get the width you declared:

table{
   display: table; /* required for table-layout to be used (not normally necessary; included for completeness) */
   table-layout:fixed; /* this keeps your columns with fixed with exactly the right width */
   width: 100%; /* table must have width set for fixed layout to work as expected */
}

and then use plain percentages on the remaining columns.

td.title, td.interpret{
    width:40%;
}
td.album{
    width:20%;
}

After using up the space for the fixed width columns, the remaining space is distributed between the columns with relative width.

But note that display: table (as opposed to say, display: block) means you can no longer have a height (including min-height and max-height).

See your modified Example.

Comments