Home > Software engineering >  table td width : as small as possible
table td width : as small as possible

Time:08-31

My table is 100% width, how can I say in CSS: "the width of columns 2 and 3 should be as small as possible, without the content breaking."

I added style width, but it's not very recommended for the responsive. I didn't found any rule to do this.

<table style="width: 100%;" >
    <tbody>
        <tr>
            <th>Name : long width</th>
            <th>Value</th>
            <th>ID</th>
        </tr>
        <tr>
            <td>This is a very long row td</td>
            <td>Yes</td>
            <td>12</td>
        </tr>
        <tr>
            <td>This is a very long row td</td>
            <td>Ni</td>
            <td>13</td>
        </tr>
    </tbody>
</table>

<p>I would like to do a bit like this (but of course without specific width) :</p>


<table style="width: 100%;" >
    <tbody>
        <tr>
            <th>Name : long width</th>
            <th style="width:40px">Value</th>
            <th style="width:40px">ID</th>
        </tr>
        <tr>
            <td>This is a very long row td</td>
            <td>Yes</td>
            <td>12</td>
        </tr>
        <tr>
            <td>This is a very long row td</td>
            <td>Ni</td>
            <td>13</td>
        </tr>
    </tbody>
</table>
Thank you !

CodePudding user response:

You can set the width on table cells and it'll still expand to fit the content. Set the width to 0 and to stop it breaking can use the white-space:nowrap; css property. Just apply it to the columns you need using the nth-child() (and derivatives) selectors. It's also good to style your table in css rather than adding the style attribute to each cell, mainly when debugging problems. See the following example:

table {
  width:100%;
}

table td:last-child, table td:nth-last-child(2)   {
  width:0px;
  white-space:nowrap;
}
<table>
    <tbody>
        <tr>
            <th>Name : long width</th>
            <th>Value</th>
            <th>ID</th>
        </tr>
        <tr>
            <td>This is a very long row td</td>
            <td>Yes and No</td>
            <td>12</td>
        </tr>
        <tr>
            <td>This is a very long row td</td>
            <td>Ni</td>
            <td>13</td>
        </tr>
    </tbody>
</table>

More info here on css selectors the white-space property

CodePudding user response:

th {
  width: 100%;
}
<table style="width: 100%;" >
    <tbody>
        <tr>
            <th>Name : long width</th>
            <th>Value</th>
            <th>ID</th>
        </tr>
        <tr>
            <td>This is a very long row td</td>
            <td>Yes</td>
            <td>12</td>
        </tr>
        <tr>
            <td>This is a very long row td</td>
            <td>Ni</td>
            <td>13</td>
        </tr>
    </tbody>
</table>

  • Related