8

I'd like to set width on the td in tbody which is underneath thead that has colspan="2" with an hard defined column width in %. The browser shell not dynamically adjust table width.

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

.sample td:nth-child(1),
.sample th:nth-child(1) {
  width: 30%;
}

.sample td:nth-child(2),
.sample th:nth-child(2) {
  width: 70%;
}
<table class="sample" border="1">
  <thead>
    <tr>
      <th colspan="2">Header</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>30%</td>
      <td>70%</td>
    </tr>
  </tbody>
</table>

The above style works if thead is removed but does not work with it.

Important notes,

  • I added the table-layout: fixed; since I need the columns to be exactly as width as specified. Using table-layoud: auto; results in the browser taking the specified width as on orientation but still dynamically adjusting width.

EDIT

The accepted answer solved my question above. However I'm not able to use colgroup since I'm using a WYSIWYG editor. Thus I added a follow up question with detailed specifications here.

Stickers
  • 75,527
  • 23
  • 147
  • 186
Manuel
  • 9,112
  • 13
  • 70
  • 110

2 Answers2

16

Try using <colgroup> and <col> tags:

.sample {
  width: 100%;
  table-layout: fixed;
}
<table class="sample" border="1">
  <colgroup>
    <col style="width:30%;">
    <col style="width:70%;">
  </colgroup>
  <thead>
    <tr>
      <th colspan="2">Header</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>30%</td>
      <td>70%</td>
    </tr>
  </tbody>
</table>
Stickers
  • 75,527
  • 23
  • 147
  • 186
0

just change your css that is so confusing for me. change it to follow

 .sample {width: 100%;}
.sample td:nth-child(1) {width:30%;}
.sample td:nth-child(2) {width:70%;}

of you wish that table looks good then you can give border so that u have clear idea about it.

<table class="sample" border="1px grey solid">
..
</table>
Kishan Oza
  • 1,707
  • 1
  • 16
  • 38