Fit cell width to content

Mansfield picture Mansfield · Jun 29, 2012 · Viewed 444.5k times · Source

Given the following markup, how could I use CSS to force one cell (all cells in column) to fit to the width of the content within it rather than stretch (which is the default behaviour)?

<style type="text/css">
td.block
{
border: 1px solid black;
}
</style>
<table style="width: 100%;">
<tr>
    <td class="block">this should stretch</td>
    <td class="block">this should stretch</td>
    <td class="block">this should be the content width</td>
</tr>
</table>

EDIT: I realize I could hard code the width, but I'd rather not do that, as the content which will go in that column is dynamic.

Looking at the image below, the first image is what the markup produces. The second image is what I want.

enter image description here

Answer

MetalFrog picture MetalFrog · Jun 29, 2012

I'm not sure if I understand your question, but I'll take a stab at it:

td {
    border: 1px solid #000;
}

tr td:last-child {
    width: 1%;
    white-space: nowrap;
}
<table style="width: 100%;">
    <tr>
        <td class="block">this should stretch</td>
        <td class="block">this should stretch</td>
        <td class="block">this should be the content width</td>
    </tr>
</table>