【发布时间】:2017-10-11 20:24:08
【问题描述】:
我正在尝试在 Sass 中强制执行某种 语义 css 类嵌套。我想强制节的 css 代码只能在节中使用,以确保在语义上应该使用 <section /> 标记。
但是在我的 Sass 文件中使用 & 时遇到了麻烦。考虑以下 html:
<section class="section-home">
<h1 class="section-home__heading">Section heading</h1>
<p class="section-home__intro">This is some random text</p>
</section>
我假设我可以在 Sass 中使用以下代码,但不行:
section {
&.section-home {
background-color: white;
&__heading {
font-size: 5rem;
}
&__intro {
color: grey;
}
}
}
Sass 将其呈现为以下 CSS:
section.section-home{background-color:#fff}
section.section-home__heading{font-size:5rem}
section.section-home__intro{color:grey}
这不是我期望或需要的,我想要的:
section.section-home{background-color:#fff}
section.section-home .section-home__heading{font-size:5rem}
section.section-home .section-home__intro{color:grey}
这是一个错误吗?我在这里做错了吗?
【问题讨论】:
-
不,这不是错误;这就是你应该预料到的。为什么
&的内部和外部使用会表现不同? -
是的,好的。但是如何使用
&?这就是使用 BEM 时 Sass 的意义所在,不是吗? -
我想要
section.section-home{background-color:#fff} section.section-home .section-home__heading{font-size:5rem} section.section-home .section-home__intro{color:grey}。请参阅 html。 -
您需要添加另一层
.section-home,因为您的预期输出中有两次(例如section.section-home .section-home__heading)。 -
我建议不要使用嵌套,尤其是在使用 BEM 时。主要是因为它使查找课程变得更加困难。如果您将类名分开,那么试图找到类“section-home__heading”是不可能的。您将不得不搜索 __heading 并且如果您的拆分类名称向上,它将出现在多个地方