gpt4 book ai didi

html - 为什么表格需要宽度 :0 to respect column widths?

转载 作者:搜寻专家 更新时间:2023-10-31 21:52:16 25 4
gpt4 key购买 nike

此表的列宽为 59px 和 100px,尽管 50px 和 100px 是指定的列宽。

table {
border-collapse: collapse;
border-spacing: 0;
table-layout: fixed;
}

col:first-child {
width: 50px;
}

col:nth-child(2) {
width: 100px;
}

td, th {
border: 1px solid black;
}
<table>
<colgroup>
<col>
<col>
</colgroup>
<thead>
<tr>
<th>Column A</th>
<th>Column B</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
</tbody>
</table>

但是如果我将 width: 0 添加到表格中,它就可以工作了。

table {
border-collapse: collapse;
border-spacing: 0;
table-layout: fixed;
width: 0;
}

col:first-child {
width: 50px;
}

col:nth-child(2) {
width: 100px;
}

td, th {
border: 1px solid black;
}
<table>
<colgroup>
<col>
<col>
</colgroup>
<thead>
<tr>
<th>Column A</th>
<th>Column B</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
</tbody>
</table>

为什么需要设置 width: 0?有更好的方法吗?>

最佳答案

可以设置max-width属性(property)给<th>元素。此外,您需要指定 box-sizing: border-box;<th><td>包含填充和边框的元素

table {
border-collapse: collapse;
border-spacing: 0;
table-layout: fixed;
}

th:first-child {
max-width: 50px;
width: 50px;
}

th:nth-child(2) {
max-width: 100px;
width: 100px;
}

td, th {
border: 1px solid black;
box-sizing: border-box;
}
<table>
<colgroup>
<col>
<col>
</colgroup>
<thead>
<tr>
<th>Column A</th>
<th>Column B</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
</tbody>
</table>

关于html - 为什么表格需要宽度 :0 to respect column widths?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51827010/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com