问题描述
我已经使用 BEM(至少是它的一个修改版本)有一段时间了;并且最近从编写 CSS 转向了 Sass,它似乎非常适合 BEM,但我不知道如何轻松地使用通配符特异性。
例如;假设我有几个按钮:
<button
class="BLOCK__ELEMENT BLOCK__ELEMENT--MODIFIER1"
>
Click Me 1
</button>
<button
class="BLOCK__ELEMENT BLOCK__ELEMENT--MODIFIER2"
>
Click Me 2
</button>
<button
class="BLOCK__ELEMENT BLOCK__ELEMENT--MODIFIER3"
>
Click Me 3
</button>
.BLOCK__ELEMENT {
border-radius: 2rem
}
.BLOCK_ELEMENT--MODIFIER1 {
background-color: red
}
.BLOCK_ELEMENT--MODIFIER2 {
background-color: white
}
.BLOCK_ELEMENT--MODIFIER3 {
background-color: blue
}
世界上一切都会好起来
在 Sass 中,我可以将其简化如下:
.BLOCK__ELEMENT {
border-radius: 2rem
&--MODIFIER1 {
background-color: red
}
&--MODIFIER2 {
background-color: white
}
&--MODIFIER3 {
background-color: blue
}
}
这是一个很好的改进
但我真正想做的是将我的标记简化如下
<button
class="BLOCK__ELEMENT--MODIFIER1"
>
Click Me 1
</button>
<button
class="BLOCK__ELEMENT--MODIFIER2"
>
Click Me 2
</button>
<button
class="BLOCK__ELEMENT--MODIFIER3"
>
Click Me 3
</button>
并让 Sass 看起来像这样:
.BLOCK__ELEMENT {
&* {
border-radius: 2rem
}
&--MODIFIER1 {
background-color: red
}
&--MODIFIER2 {
background-color: white
}
&--MODIFIER3 {
background-color: blue
}
}
sass 中是否有这样的通配符实现?
解决方法
好的旧css怎么样? :)
[class*="BLOCK__ELEMENT-"]
,
我有另一个可能的解决方案
@use "sass:string"
@mixin self() {
$self: string.slice(#{&},2);
@at-root &,[class*="#{$self}"] {
@content
}
}
.Block {
@include self() {
border-radius: 2rem;
}
&--modifier1 {
background-color: red;
}
&--modifier2 {
background-color: blue;
}
&--modifier1 {
background-color: salmon;
}
&__element {
@include self() {
width: 50px;
}
&--modifier {
background-color: skyblue;
}
}
}
这是这样编译的
.Block,[class*=Block] {
border-radius: 2rem;
}
.Block--modifier1 {
background-color: red;
}
.Block--modifier2 {
background-color: blue;
}
.Block--modifier1 {
background-color: salmon;
}
.Block__element,[class*=Block__element] {
width: 50px;
}
.Block__element--modifier {
background-color: skyblue;
}
,
就像 Sueno 一样,您可以使用 [class*="BLOCK__ELEMENT--"] 并执行以下操作:
.BLOCK_ELEMENT {
@at-root &,[class*="BLOCK_ELEMENT"] { // or just @at-root [class*="BLOCK_ELEMENT"]
border-radius: 2rem;
}
&--MODIFIER1 {
background-color: red
}
&--MODIFIER2 {
background-color: white
}
&--MODIFIER3 {
background-color: blue
}
}