TransWikia.com

HTML table widths set proportionally

Stack Overflow Asked by Mayur Arora on January 27, 2021

I have a fixed-layout table, with two columns. If I set the width of just one column, things are as expected ( at least how I expected them to be).

However, if I specify the widths of both the columns, cells start dividing themselves proportionally.

table {
  table-layout: fixed;
  width: 120px;
  border-collapse: collapse;
}

td {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  padding: 0;
}

td:first-child {
  width: 5%;
}

td:nth-child(2) {
  width: 2%;
}
<table>
    <tr>
      <td>Ed</td>
      <td>Wood</td>
    </tr>
    <tr>
      <td>Albert</td>
      <td>Schweitzer</td>
    </tr>
    <tr>
      <td>Jane</td>
      <td>Fonda</td>
    </tr>
    <tr>
      <td>William</td>
      <td>Shakespeare</td>
    </tr>
  </table>

What I intended was for the first column to take 5% of the row width ( 120 px ) and the second column to take 2% of the row width. However, the first one takes 5/7 of the row width and the second one takes 2/7 of the row width.

Is there some spec that details this behavior?

One Answer

As mentioned by Itay, the total width has to match the width of the table. When you set the width of one column the only thing that happens is that first column takes 5% and the other ones take remaining 95%, if you add width to all, they split the space piece by piece until they reach 100%.

One way you could get what you're trying to achieve is have an empty column like this

table {
  table-layout: fixed;
  width: 120px;
  border-collapse: collapse;
  background: whitesmoke;
}

td {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  padding: 0;
}

td:first-child {
  width: 5%;
}

td:nth-child(2) {
  width: 2%;
}

td:last-child {
  width: auto;
}
<table>
  <tr>
    <td>Ed</td>
    <td>Wood</td>
    <td></td>
  </tr>
  <tr>
    <td>Albert</td>
    <td>Schweitzer</td>
    <td></td>
  </tr>
  <tr>
    <td>Jane</td>
    <td>Fonda</td>
    <td></td>
  </tr>
  <tr>
    <td>William</td>
    <td>Shakespeare</td>
    <td></td>
  </tr>
</table>

That way, the empty column will be taking that remaining space and let your other columns have the width you specified. And if you do decide that you want the rows to span the full width of the table, width: auto will be 0 and shouldn't cause you any problems.

Answered by Senatrius on January 27, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP