我有以下 CSS 来格式化带有一些粘性标题的表格:
div {
position: relative;
z-index: 1;
overflow: scroll;
height: 350px;
width: 500px;
}
table {
width: 100%;
margin: auto;
border-collapse: separate;
border-spacing: 0;
}
th, td {
padding: 5px 10px;
border: 1px solid #000;
background: #fff;
vertical-align: top;
}
th {
color: #000;
position: -webkit-sticky;
position: sticky;
top: 0;
}
th:first-child {
left: 0;
z-index: 6;
}
td:first-child {
position: -webkit-sticky;
position: sticky;
left: 0;
z-index: 2;
background: #ccc;
}
thead th {
z-index: 5;
}
th:after {
content: "";
display: inline-block;
vertical-align: inherit;
height: 0;
width: 0;
border-width: 5px;
border-style: solid;
border-color: transparent;
margin-right: 1px;
margin-left: 10px;
float: right;
}
th[data-sorted="initial"]:after {
visibility: visible;
border-top-color: #ccc;
margin-top: 5px;
}
th[data-sorted="true"]:after {
visibility: visible;
}
th[data-sorted-direction="descending"]:after {
border-top-color: inherit;
margin-top: 7px;
}
th[data-sorted-direction="ascending"]:after {
border-bottom-color: inherit;
margin-top: 2px;
}
这是一个 Codepen 展示它:
https://codepen.io/anon/pen/jQjazq
如果您点击“最小值”列,箭头会出现在其下方。这看起来很愚蠢。使用CSS,我该如何制作,以便列的宽度考虑到箭头,以便默认情况下它们更宽?
最佳答案
我处理这种情况的方法是对父元素应用填充,并对伪元素应用相应的负边距,这样如果换行,它就会换行整个元素。
在您的示例中,我稍微更改了选择器以定位 strong
而不是 th
。但除此之外,关键的变化是第 strong
上的样式和第 strong:after
上的 margin-right
。
https://codepen.io/anon/pen/mayWja
th strong {
display: inline-block;
padding-right: 20px;
}
th strong:after {
content: "";
display: inline-block;
vertical-align: inherit;
height: 0;
width: 0;
border-width: 5px;
border-style: solid;
border-color: transparent;
margin-right: -20px;
margin-left: 10px;
float: right;
}
th[data-sorted="initial"] strong:after {
visibility: visible;
border-top-color: red;
margin-top: 5px;
}
th[data-sorted="true"] strong:after {
visibility: visible;
}
th[data-sorted-direction="descending"] strong:after {
border-top-color: inherit;
margin-top: 7px;
}
th[data-sorted-direction="ascending"] strong:after {
border-bottom-color: inherit;
margin-top: 2px;
}
关于html - 如何使 "after"伪元素始终位于表头中的同一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53711100/