我不知道为什么我的边框样式不适用于 position: sticky;
属性。我想在我的粘性表格标题上设置边框样式。但我不想使用透明背景色。我怎样才能实现它?这是我的问题和 JSFiddle Link 的示例代码
#wrapper {
width: 400px;
height: 200px;
overflow: auto;
}
table {
width: 100%;
text-align: center;
border-collapse: collapse;
}
table tr th,
table tr td {
border: 2px solid;
}
table thead th {
position: -webkit-sticky;
position: sticky;
top: 0;
background-color: #edecec;
}
<div id="wrapper">
<table>
<thead>
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
<th>E</th>
</tr>
</thead>
<tr>
<td>1</td>
<td>1</td>
<td>1</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>2</td>
<td>2</td>
<td>2</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>3</td>
<td>3</td>
<td>3</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>4</td>
<td>4</td>
<td>4</td>
<td>4</td>
</tr>
<tr>
<td>5</td>
<td>5</td>
<td>5</td>
<td>5</td>
<td>5</td>
</tr>
<tr>
<td>6</td>
<td>6</td>
<td>6</td>
<td>6</td>
<td>6</td>
</tr>
<tr>
<td>7</td>
<td>7</td>
<td>7</td>
<td>7</td>
<td>7</td>
</tr>
<tr>
<td>8</td>
<td>8</td>
<td>8</td>
<td>8</td>
<td>8</td>
</tr>
<tr>
<td>9</td>
<td>9</td>
<td>9</td>
<td>9</td>
<td>9</td>
</tr>
<tbody>
</tbody>
</table>
</div>
以下是我想要的截图以及我的问题还不够清楚的人。
您可以看到 th
的内联边框样式不起作用(删除 css 的 position
属性,您会看到四周有边框。)。
向下滚动一点后。您会看到所有边框样式都消失了。
最佳答案
出现问题是因为使用了border-collapse: collapse
.当浏览器折叠边框时,<th>
上的顶部和底部边框必须应用于周围的元素——<table>
的顶部边框和以下 <tr>
的底部边框.
如果您使用 border-collapse: separate
并使边框位于一侧,边框将真正附加到 <th>
,按预期保持固定,并出现折叠。
以下是可应用于您的 HTML 代码段的示例样式。
#wrapper {
width: 400px;
height: 200px;
overflow: auto;
}
table {
width: 100%;
text-align: center;
border-collapse: separate; /* Don't collapse */
border-spacing: 0;
}
table th {
/* Apply both top and bottom borders to the <th> */
border-top: 2px solid;
border-bottom: 2px solid;
border-right: 2px solid;
}
table td {
/* For cells, apply the border to one of each side only (right but not left, bottom but not top) */
border-bottom: 2px solid;
border-right: 2px solid;
}
table th:first-child,
table td:first-child {
/* Apply a left border on the first <td> or <th> in a row */
border-left: 2px solid;
}
table thead th {
position: sticky;
top: 0;
background-color: #edecec;
}
关于html - 边框样式不适用于粘性位置元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50361698/