Alex Craft
Alex Craft

Reputation: 15336

Why HTML Table column width doesn't work with fixed-layout and 100% width?

When table use fixed-layout and I set its width to 100% it ignores the column width and makes it all even. Why?

This is how the table look without 100% width.

enter image description here

But when I set table width as 100% all columns became even

enter image description here

How to fix that? I can't remove 'fixed-layout' or the 'merged th', I need it both, and also need to make table 100% wide.

(actually I can detect that table uses 100% width and replace 'merged th' with div before the table, but would be better to find a proper way to fix it)

The code

<style>
  th, td { border: 1px solid black; }
  table {
    width: 100%;
    table-layout: fixed;
  }
</style>

<table>
  <tr>
    <th colspan="2" width="100%">100% united th</th>
  </tr>
  <tr>
    <th style="width: 20%;">20% th</th>
    <th style="width: 80%;">80% th</th>
  </tr>
  <tr>
    <td>a</td>
    <td>b</td>
  </tr>
</table>

Upvotes: 2

Views: 2923

Answers (1)

Alex Craft
Alex Craft

Reputation: 15336

Seems like the <colgroup> should be used to fix that, related question explaining why it happens.

<style>
  th, td { border: 1px solid black; }
  table {
    width: 100%;
    table-layout: fixed;
  }
</style>

<table>
  <colgroup>
    <col style="width: 20%;">
    <col style="width: 80%;">
  </colgroup>
  <tr>
    <th colspan="2" width="100%">100% united th</th>
  </tr>
  <tr>
    <th>20% th</th>
    <th>80% th</th>
  </tr>
  <tr>
    <td>a</td>
    <td>b</td>
  </tr>
</table>

Upvotes: 1

Related Questions