Is there any alternative to colgroup col width attribute now it has been deprecated?
Asked Answered
O

1

8

The MDN page on colgroup indicates that col width is deprecated, however I have not found an alternative when colspan is involved, and you need to specify the width of a "colspanned" column.

Below is a rather minimalistic snippet to illustrate the issue, for a table with three columns and two rows. The middle column is never explicited with a "td" elements.

With a colgroup, it is possible to specify its width, and then everything is well. Without colgroup, the HTML rendering engine is unable to solve the equation, and column widths render incorrectly.

  table {
    border-collapse: collapse;
  }
  .w100 { width: 100px; background-color: red }
  .w200 { width: 200px; background-color: green }
<!DOCTYPE html>
<html>
<body>
With colgroups  
<table>
  <colgroup>
    <col style="width:100px">
    <col style="width:100px">
    <col style="width:100px">
  </colgroup>
  <tbody>
    <tr>
      <td class="w100">A
      <td class="w200" colspan="2">B
    <tr>
      <td class="w200" colspan="2">C
      <td class="w100">D
  </tbody>
</table>
    
<p></p>

No colgroups    
<table>
  <tbody>
    <tr>
      <td class="w100">A
      <td class="w200" colspan="2">B
    <tr>
      <td class="w200" colspan="2">C
      <td class="w100">D
  </tbody>
</table>
    
</body>
</html>
Oft answered 11/5, 2021 at 13:3 Comment(1)
Can you clarify what you find incorrect about the rendering? I cannot see any difference between both results, either with Google Chrome or Firefox 114.0.Oligarch
J
6

The official solution is using :nth-child in CSS.

.table_8 td:nth-child(1) {
    text-align: right;
    width: 32px;
}

But this is very unpractical! In my opinion, col width should be de-deprecated. It is supported by all browsers, as far as I can see. https://caniuse.com/?search=col%20width

Jovial answered 22/5, 2021 at 5:57 Comment(3)
Firefox no longer supports it correctly, I only found out about the deprecation through an end-user bug report about incorrect column width :/Oft
Even if a properly targeted selector can be found, this would be unreliable due to td colspan. td:nth-child(3) can target different cells/columns depending on the row. What makes you think this solution would be "official"?Oligarch
I fully agree with your points. I'm not saying, that this solution is good, I wrote "official", because that's the solution according to the standards. I would also like to have better options.Jovial

© 2022 - 2024 — McMap. All rights reserved.