html - 如何使 "after"伪元素始终位于表头中的同一行?

标签 html css css-selectors css-tables pseudo-element

我有以下 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/

相关文章:

html - 事件单元格的边界不应延伸到相邻单元格

html - <li> 元素的元数据属性

javascript - 直线对齐

jquery - Position-absolute jquery内联表单验证错误框位置

css - 是否有 CSS 父级选择器?

html - 当内容不适合窗口时使 <div> 水平滚动

javascript - chrome 中的 onmouseover(下拉 - 选项标签)事件不起作用 - php,javascript

javascript - 如何在angularjs中根据索引值显示li标签

javascript - 我如何在不使用 JavaScript 的情况下使用 JQuery 库来重写它?

html - 悬停在第 n 个 child 上的问题