设置宽度下与 <td> <th> colspan



我想在tbodytd上设置宽度,该宽度位于thead下方,该具有硬定义的列宽(以%为单位)colspan="2"%。浏览器外壳不会动态调整表宽。

.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>

如果删除thead则上述样式有效,但不适用于它。

重要说明,

  • 我添加了table-layout: fixed;,因为我需要列的宽度与指定的宽度完全相同。使用table-layoud: auto;会导致浏览器将指定的宽度作为方向,但仍动态调整宽度。

编辑

接受的答案解决了我上面的问题。但是我无法使用colgroup,因为我使用的是所见即所得的编辑器。因此,我在这里添加了一个带有详细规范的后续问题。

尝试使用<colgroup><col>标签:

.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>

只是更改您的 CSS,这对我来说太混乱了。 将其更改为关注

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

你希望那张表看起来不错,然后你可以给边框,这样你就清楚了。

<table class="sample" border="1px grey solid">
..
</table>

最新更新