如何在Sass的.item块内嵌套父类.open样式,仅保留两个代码块
嵌套父类状态样式到子元素代码块的实现方案
你需要把父元素.item带.open类时的样式规则,分别嵌套到.info和.inner-info的代码块中,最终在.item{}内只保留这两个子元素的代码块。可以通过SCSS的@at-root规则结合父选择器引用来实现:
最终SCSS代码:
.item { .info { display: flex; /* some other stuff */ // 父元素带.open类时的样式 @at-root #{&/..}.open & { display: none; } } .inner-info { display: none; /* some other stuff */ // 父元素带.open类时的样式 @at-root #{&/..}.open & { display: flex; } } }
说明:
#{&/..}是SCSS 1.3及以上版本支持的语法,用来获取当前选择器的父级(即.item),避免硬写类名,保持代码灵活性。- 如果你的SCSS版本不支持
&/..,可以直接硬写父类名:
.item { .info { display: flex; /* some other stuff */ @at-root .item.open & { display: none; } } .inner-info { display: none; /* some other stuff */ @at-root .item.open & { display: flex; } } }
编译后的CSS会自动生成你需要的规则:
.item .info { display: flex; /* some other stuff */ } .item.open .info { display: none; } .item .inner-info { display: none; /* some other stuff */ } .item.open .inner-info { display: flex; }
内容的提问来源于stack exchange,提问作者Wolforce
相关产品推荐
相关产品推荐

