将第一个 tr 设置为 fixed 而不丢失宽度
Set the first tr to fixed without losing the width
这是我的 fiddlejs:[https://jsfiddle.net/uj8gbeL1/]
我试图修复 table 的第一行,但是当我尝试设置样式时 postion:fixed
,该行的宽度不同
如何在不为每个元素设置“静态”宽度的情况下解决此问题?
您将使用以下方法解决此问题:
<tr class="globalTr" style="position:sticky;top:0;z-index:1">
或者更好,把它放在 css:
.globalTr:first-child {
position: sticky;
top: 0;
z-index: 1;
}
但是,您的代码可以格式化得更好。
这是一个例子,请阅读html中的评论:
div {
width: 100%;
height: 200px;
overflow: auto;
}
table {
font-family: sans-serif;
border-collapse: collapse;
}
thead {
position: sticky;
top: 0;
z-index: 1;
}
th, td {
border: 1px solid #369;
padding: 10px;
}
th {
background: #369;
color: white;
}
td {
background: aliceblue;
}
<div>
<table>
<thead>
<tr>
<th>Heading1</th> <!-- th is for headings -->
<th>Heading2</th>
</tr>
</thead>
<!-- use thead and tbody -->
<tbody>
<tr>
<td>Content</td> <!-- td is for cells -->
<td>Content</td>
</tr>
<tr>
<td>Content</td>
<td>Content</td>
</tr>
<tr>
<td>Content</td>
<td>Content</td>
</tr>
<tr>
<td>Content</td>
<td>Content</td>
</tr>
<tr>
<td>Content</td>
<td>Content</td>
</tr>
<tr>
<td>Content</td>
<td>Content</td>
</tr>
</tbody>
</table>
</div>
使用CSS position:sticky;top:0;
代替position:fixed;
。
这是我的 fiddlejs:[https://jsfiddle.net/uj8gbeL1/]
我试图修复 table 的第一行,但是当我尝试设置样式时 postion:fixed
,该行的宽度不同
如何在不为每个元素设置“静态”宽度的情况下解决此问题?
您将使用以下方法解决此问题:
<tr class="globalTr" style="position:sticky;top:0;z-index:1">
或者更好,把它放在 css:
.globalTr:first-child {
position: sticky;
top: 0;
z-index: 1;
}
但是,您的代码可以格式化得更好。
这是一个例子,请阅读html中的评论:
div {
width: 100%;
height: 200px;
overflow: auto;
}
table {
font-family: sans-serif;
border-collapse: collapse;
}
thead {
position: sticky;
top: 0;
z-index: 1;
}
th, td {
border: 1px solid #369;
padding: 10px;
}
th {
background: #369;
color: white;
}
td {
background: aliceblue;
}
<div>
<table>
<thead>
<tr>
<th>Heading1</th> <!-- th is for headings -->
<th>Heading2</th>
</tr>
</thead>
<!-- use thead and tbody -->
<tbody>
<tr>
<td>Content</td> <!-- td is for cells -->
<td>Content</td>
</tr>
<tr>
<td>Content</td>
<td>Content</td>
</tr>
<tr>
<td>Content</td>
<td>Content</td>
</tr>
<tr>
<td>Content</td>
<td>Content</td>
</tr>
<tr>
<td>Content</td>
<td>Content</td>
</tr>
<tr>
<td>Content</td>
<td>Content</td>
</tr>
</tbody>
</table>
</div>
使用CSS position:sticky;top:0;
代替position:fixed;
。