2

Is there a way to set td width by number of td in a table. e.g:

  • if there is 1 td, then the width of each td is 100%
  • if there is 2 td, then the width of each td is 50%
  • if there is 3 td, then the width of each td is 1/3
  • etc.

Is there a way to write a CSS rule for this need?

Side note: I can not edit the HTML, it comes from somwhere else. I can only edit CSS.

The HTML could look like this:

<table>
  <tr>
    <td>foo</td>
    <td>bar</td>
    <td>baz<td>
  </tr>
</table>
rap-2-h
  • 30,204
  • 37
  • 167
  • 263

1 Answers1

5

You can use table-layout:fixed with width:100% to the table.

table-layout: fixed

Table and column widths are set by the widths of table and col elements or by the width of the first row of cells

table {
  width: 100%;
  table-layout: fixed;
}

td {
  border: 1px solid;
}
<table>
  <tr>
    <td>foo</td>
  </tr>
</table>
<br>
<table>
  <tr>
    <td>foo</td>
    <td>bar</td>
  </tr>
</table>
<br>
<table>
  <tr>
    <td>foo</td>
    <td>bar</td>
    <td>baztd</td>
  </tr>
</table>
<br>
<table>
  <tr>
    <td>foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo</td>
    <td>bar</td>
    <td>foo</td>
    <td>bar</td>
  </tr>
</table>
Bhuwan
  • 16,525
  • 5
  • 34
  • 57