-1

I have a table and want all columns to be the same width (irrespective of content), except for the last one, which is supposed to be 20px narrower than the first two.

td:nth-child(3) { width: calc(100% - 20px); } breaks the layout unfortunately.

I am aware of similar questions (CSS calc not working for <td> width), but unfortunately, no working solution is given. Is this not possible with pure CS??

table {
  width: 100%;
  table-layout: fixed;
}
td { border: 1px solid red; }

td:nth-child(1) { width: 100%; }
td:nth-child(2) { width: 100%; }
td:nth-child(3) { width: calc(100% - 20px); }
<table>
  <tr>
    <td>l</td>
    <td>lol</td>
    <td>3</td>
  </tr>
</table>
Tonald Drump
  • 1,227
  • 1
  • 19
  • 32

1 Answers1

0

You could use max-content for a single row:

to apply the width of the widest td from the third column will require JavaScript.

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

td {
  border: 1px solid red;

}

td:nth-child(3) {
    width:max-content ;
}
<table>
  <tr>
    <td>l</td>
    <td>lol</td>
    <td>3</td>
  </tr>
</table>
<hr>
<table>
  <tr>
    <td>l</td>
    <td>lol</td>
    <td>333</td>
  </tr>
</table>

Here is a JavaScript possible approach :

var bigW = "0";
var myTable = document.querySelector("table#test");
myTable.style.width = "auto"; //remove width 

for (let td3 of document.querySelectorAll("td:last-of-type")) { // check width of last td in each row
  td3W = td3.offsetWidth; // get width
  if (td3W > bigW) { // is it the biggest value ?
    bigW = td3W;
  }
  document.documentElement.style.setProperty("--myW", bigW + "px"); // update css var()
  myTable.style.width = "100%"; //reset width
}
table {
  width: 100%;
  table-layout: fixed;
}

td {
  border: 1px solid red;
}

td:last-of-type {
  width: var(--myW, 2em);/* if var not set, then use default value*/
}
<table id="test">
  <tr>
    <td>l</td>
    <td>lol</td>
    <td>3</td>
  </tr>
  <tr>
    <td>l</td>
    <td>lol</td>
    <td>32 12</td>
  </tr>
  <tr>
    <td>l</td>
    <td>lol</td>
    <td>3333333333</td>
  </tr>
  <tr>
    <td>l</td>
    <td>lol</td>
    <td>3</td>
  </tr>
</table>
G-Cyrillus
  • 101,410
  • 14
  • 105
  • 129