如何嵌套SCSS伪选择器以精简重复的伪元素代码?
优化方案
你可以通过合并公共规则、拆分差异属性的方式来精简代码,避免重复书写相同样式:
&::before { content: ''; position: absolute; width: 1px; background: ${(props) => props.theme.colors.link}; right: 6px; height: 100%; // 默认高度 } // 合并:first-child和:last-child的共同修改 &:first-child::before, &:last-child::before { height: 50%; } // 单独设置各自的位置属性 &:first-child::before { bottom: 0; } &:last-child::before { top: 0; }
思路说明
- 基础样式抽离:把所有伪元素的公共属性(
content、position、width、background、right)放在基础的&::before规则里,只保留默认的height:100%; - 合并公共修改:
:first-child和:last-child的伪元素都需要修改height为50%,把这部分合并到一个规则里,减少重复代码; - 单独设置差异属性:最后只给两个伪元素分别设置
bottom和top这两个独有的属性即可。
你之前尝试嵌套到&::before里失败的原因:SCSS的父选择器&在&::before内部代表的是::before伪元素,而非当前元素,嵌套:first-child会生成::before:first-child这种无效选择器,而你需要的是:first-child::before(当前元素为第一个子元素时的伪元素),因此必须把:first-child放在当前元素选择器上,而非伪元素之后。
内容的提问来源于stack exchange,提问作者dokichan
相关产品推荐
相关产品推荐

