htmlcsshtml-table

Fit cell width to content


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)?

td.block {
  border: 1px solid black;
}
<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>

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


Solution

  • 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>