假设我使用BEM和SCSS为通用列表组件提供以下CSS: .list { &__item { &:not(:last-child) { margin-right: .3em
... . . 假设我使用BEM和SCSS为通用列表组件提供以下CSS:
.list { &__item { &:not(:last-child) { margin-right: .3em; } }}
我想添加一个可以使列表垂直的修饰符,如下所示:
.list--vertical { display: flex; flex-direction: column;}
当我考虑list__item元素的余量时,我的问题出现了.对于垂直列表,我希望我的边距位于底部,而不是每个项目的右边.如果我正确理解BEM,我无法根据列表的修饰符修改list__item的样式,这是正确的吗?
更确切地说,这就是我想要做的:
.list--vertical { display: flex; flex-direction: column; .list__item { &:not(:last-child) { margin-bottom: .3em; margin-right: 0; } }}
使用BEM处理此问题的可接受方法是什么? list__item的另一个修饰符处理边距?另一块完全用于垂直列表?
.解决方法
. .What is the accepted way of dealing with this using BEM?
.取决于您正在使用的BEM版本.我使用a variant of the pre-spec concept of BEM,这意味着如果您遵循bem.info,您将获得不同的答案.
修饰符应附加到它们修改的元素上.但是,修改块允许修饰符由子元素继承:
<div class="foo foo--example"> <div class="foo__bar foo--example__bar">...</div><div>
当子元素也具有修饰符时,这会变得混乱:
<div class="foo foo--example"> <div class=" foo__bar foo--example__bar foo__bar--another-example foo--example__bar--another-example">...</div><div>
这种形式的BEM语法非常冗长.它最好用于生成的代码.
我使用LESS进行CSS预处理,因此我的BEM代码通常如下所示:
.foo { ... &__bar { ... }}
使用修饰符,它变为:
.foo { ... &__bar { ... } &--example { ... &__bar { ... } }}
这强制了级联的顺序正确,并且所有选择器仍然只有一个类.
. . .. ...