我想在顶部滚动时使用标题修复来创建表格,而 th 宽度将根据 td 所包含的数据而变化。滚动时我可以固定标题。
table {
width: 500px;
border-collapse: collapse;
}
thead {
display: block;
width: 500px;
overflow: auto;
color: #fff;
background: #000;
}
tbody {
display: block;
width: 500px;
height: 100px;
background: pink;
overflow: auto;
}
th,
td {
padding: .5em 1em;
text-align: left;
vertical-align: top;
border-left: 1px solid #fff;
}
<h2>HTML Table</h2>
<table>
<thead>
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
</thead>
<tbody>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
<tr>
<td>Ernst Handel</td>
<td>Roland Mendel</td>
<td>Austria</td>
</tr>
<tr>
<td>Island Trading</td>
<td>Helen Bennett</td>
<td>UK</td>
</tr>
<tr>
<td>Laughing Bacchus Winecellars</td>
<td>Yoshi Tannamuri</td>
<td>Canada</td>
</tr>
<tr>
<td>Magazzini Alimentari Riuniti</td>
<td>Giovanni Rovelli</td>
<td>Italy</td>
</tr>
</tbody>
</table>
但是问题是我必须为每个 th 分别分配宽度:
th:nth-child(1){
width: 50px;
}
th:nth-child(2){
width: 20px;
}
th:nth-child(3){
width: 20px;
}
但是我想使<th>
的宽度也能保持动态。