position:sticky使用此属性固定列,如何将固定列设置隔行变色
时间: 2023-11-27 12:53:34 浏览: 30
可以通过 CSS 中的伪类选择器 `:nth-of-type()` 来实现隔行变色,结合 `position: sticky` 属性,示例代码如下:
HTML代码:
```html
<table>
<thead>
<tr>
<th>列1</th>
<th>列2</th>
<th>列3</th>
</tr>
</thead>
<tbody>
<tr>
<td>内容1</td>
<td>内容2</td>
<td>内容3</td>
</tr>
<tr>
<td>内容4</td>
<td>内容5</td>
<td>内容6</td>
</tr>
<tr>
<td>内容7</td>
<td>内容8</td>
<td>内容9</td>
</tr>
<tr>
<td>内容10</td>
<td>内容11</td>
<td>内容12</td>
</tr>
</tbody>
</table>
```
CSS代码:
```css
table {
border-collapse: collapse;
}
thead th {
position: sticky;
top: 0;
background-color: #fff;
}
tbody tr:nth-of-type(odd) {
background-color: #f6f6f6;
}
```
在上面的代码中,我们使用了 `:nth-of-type(odd)` 选择器来设置隔行变色,将奇数行的背景色设置为灰色。同时,为了使表格头部固定在页面顶部,我们使用了 `position: sticky` 属性和 `top: 0` 来实现。