You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为一组CSS选择器设置:before伪元素属性

给一组CSS选择器统一设置:before伪元素属性的正确写法

嘿,我明白你想把原来针对多个元素的样式,改成给这些元素的::before伪元素设置属性。不过先纠正一个小误区:你期望的那种用括号把选择器组包起来再加::before的写法,在CSS里是不生效的哦——CSS伪元素需要附着在每一个单独的选择器后面,不能给整个选择器组统一加。

原来的代码(针对元素本身)

.two-row-two-column mat-grid-tile:nth-of-type(3) .serveroutput-pop, 
.two-row-two-column mat-grid-tile:nth-of-type(1) .serveroutput-pop, 
.two-row-three-column mat-grid-tile:nth-of-type(2) .serveroutput-pop, 
.one-row-two-column mat-grid-tile:nth-of-type(1) .serveroutput-pop { 
  left: -397px; 
  right: auto; 
}

修改后的正确代码(针对每个元素的::before伪元素)

只需要给选择器组里的每一个选择器末尾都加上::before,就能实现你要的效果:

.two-row-two-column mat-grid-tile:nth-of-type(3) .serveroutput-pop::before, 
.two-row-two-column mat-grid-tile:nth-of-type(1) .serveroutput-pop::before, 
.two-row-three-column mat-grid-tile:nth-of-type(2) .serveroutput-pop::before, 
.one-row-two-column mat-grid-tile:nth-of-type(1) .serveroutput-pop::before { 
  left: -458px; 
  right: auto; 
}

关键说明

  • CSS的伪元素(比如::before/::after)是选择器的一部分,必须跟在具体的元素选择器后面,不能通过括号分组后统一添加。
  • 如果你觉得代码重复度高,可以考虑用CSS变量或者预处理器(比如Sass/Less)的混合宏来简化,但原生CSS只能用这种逐个添加的方式。

内容的提问来源于stack exchange,提问作者Lijo Vijayan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 08:49:04