【发布时间】:2022-06-28 17:41:59
【问题描述】:
这已经讨论过很多次了,但我还没有看到一个正确的答案。我想在我的代码中使用 BEM 方法,但我想保留高级 SASS 嵌套选项以提高代码可读性。
这是我的代码示例:
<div class="education">
<h3 class="education__heading">Heading</h3>
<div class="education__items">
<div class="education__item">
<h4 class="education__faculty">Lorem ipsum</h4>
<span class="education__subject">Dolor sit amet</div>
</div>
</div>
</div>
这应该是具有 3 层嵌套的正确 BEM 模型。这个模型的 SASS 代码如下所示:
.education {
&__heading {
}
&__items {
}
&__item {
}
&__faculty {
}
&__subject {
}
}
据我所知,这是正确的方法,但我错过了在我的 SASS 代码中嵌套类的选项(参见下面的简化示例,没有 BEM 类名):
.education {
.heading {
}
.items {
.item {
.faculty {
}
.subject {
}
}
}
}
这个结构基本上复制了HTML结构,我相信它很容易维护和阅读。 在使用正确的 BEM 方法时,是否可以在 SASS 中保留多级嵌套?
【问题讨论】:
-
您确定要为您的选择器提供如此多的特异性吗?它将编译为:
.education .items . item .faculty {}...如果这确实是您想要的,只需在您的父选择器级别创建一个变量,并使用它而不是与符号&。 -
@AmauryHanser 这是一个很好的观点,谢谢。虽然这个简化的例子并不是最好的例子,但我同意在大多数情况下,超过 3 个级别的特异性是多余的。