【问题标题】:Shorten verbose CSS that repeats combinations of elements and pseudo-classes缩短重复元素和伪类组合的冗长 CSS
【发布时间】:2021-11-29 19:12:03
【问题描述】:

我将不同的伪类和元素添加到表的相同部分。有没有办法通过以某种方式总结它们来节省工作和精力?我不知道该怎么做。

.tr1 th:nth-child(1) {background-color: green;}
.tr1 th:nth-child(5) {background-color: green;}
.tr2 td:nth-child(2) {background-color: green;}
.tr2 td:nth-child(4) {background-color: green;}
.tr3 td:nth-child(3) {background-color: green;}
.tr4 td:nth-child(4) {background-color: green;}
.tr4 td:nth-child(2) {background-color: green;}

.tr1 th:nth-child(1):hover {background-color: hotpink;}
.tr1 th:nth-child(5):hover {background-color: hotpink;}
.tr2 td:nth-child(2):hover {background-color: hotpink;}
.tr2 td:nth-child(4):hover {background-color: hotpink;}
.tr3 td:nth-child(3):hover {background-color: hotpink;}
.tr4 td:nth-child(4):hover {background-color: hotpink;}
.tr4 td:nth-child(2):hover {background-color: hotpink;}

.tr1 th:nth-child(1)::selection {color: hotpink;}
.tr1 th:nth-child(5)::selection {color: hotpink;}
.tr2 td:nth-child(2)::selection {color: hotpink;}
.tr2 td:nth-child(4)::selection {color: hotpink;}
.tr3 td:nth-child(3)::selection {color: hotpink;}
.tr4 td:nth-child(4)::selection {color: hotpink;}
.tr4 td:nth-child(2)::selection {color: hotpink;}

【问题讨论】:

  • 看看 SCSS 是否能满足您的需求。它有一个&,意思是“重复上一个选择器”,你可以在它后面添加一个伪元素选择器,如下所示:css-tricks.com/the-sass-ampersand/…

标签: css html-table css-selectors


【解决方案1】:

您可以使用:is() 和逗号, 组合选择器

.tr1 th:is(:nth-child(1),:nth-child(5)),
:is(.tr2,.tr4) td:is(:nth-child(2),:nth-child(4)),
.tr3 td:nth-child(3) {background-color:green}

.tr1 th:is(:nth-child(1),:nth-child(5)):hover,
:is(.tr2,.tr4) td:is(:nth-child(2),:nth-child(4)):hover,
.tr3 td:nth-child(3):hover {background-color:hotpink}

.tr1 th:is(:nth-child(1),:nth-child(5))::selection,
:is(.tr2,.tr4) td:is(:nth-child(2),:nth-child(4))::selection,
.tr3 td:nth-child(3)::selection {color:hotpink}

【讨论】:

    猜你喜欢
    • 2012-06-30
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    • 2011-12-21
    • 2011-01-22
    相关资源
    最近更新 更多