问题描述
我最近听说了BEM方法.
I recently heard about BEM methodology.
- BEM方法的确切用途是什么?
- BEM以什么方式使我们的工作更轻松?
- 使用BEM是一种好习惯吗?
推荐答案
BEM是一种命名方法.它代表块元素修饰符",其目的是促进模块化并使样式和类易于维护.
BEM is a naming methodology. It stands for Block Element Modifier and it's aim is to facilitate modularity and make styles and classes a lot easier to maintain.
要在回复中解释它并不容易,但是我可以给你基本的想法.
It's not easy to explain it in a reply, but I can give you the basic idea.
因此,如果您正在考虑菜单,那么整个元素/组件结构将是:
So if you're thinking of a menu, then the whole element / component structure would be:
阻止:菜单元素:项目修饰符:水平,垂直
Block: menuElement: itemModifier(s): horizontal, vertical
通过遵循标准的BEM约定,您将在CSS中编写如下内容:
And by following standard BEM conventions, you would write something like this in CSS:
html,
body {
height: 100%;
}
.menu {
display: block;
}
.menu__item {
display: inline-block;
line-height: 30px;
width: 100px;
}
.menu--horizontal {
width: 100%;
height: 30px;
}
.menu--vertical {
width: 100px;
height: 100%;
}
.menu--horizontal .menu__item {
border-right: 1px solid #e5e5e5;
text-align: center;
}
.menu--vertical .menu__item {
border-bottom: 1px solid #e5e5e5;
text-align: left;
}
<div class="menu menu--horizontal">
<div class="menu__item">Home</div>
<div class="menu__item">About</div>
<div class="menu__item">Contact</div>
</div>
从代码中可以看到,元素与块之间有2个下划线,修饰符之间有2个破折号.
As you see from the code, the elements are separated from the block with 2 underscores and modifiers are separated with 2 dashes.
现在,如果将菜单上的修改器从--horizontal
更改为--vertical
,则将同时为块和其中的元素选择特定的修改器样式.
Now if you change the modifier on the menu from --horizontal
to --vertical
, the specific modifier styles will be picked up for both the block and the element inside.
这应该是一个基本示例,但它应该使您了解这种方法的强大之处,因为它可以将任何组件拆分为这些基本的块元素修饰符结构,从而使维护起来轻而易举.
This should be a basic example, but it should give you an idea of how powerful this methodology is, because it allows splitting any component into these basic block-element-modifier structures, making everything a breeze to maintain.
也可以使用像SASS这样的预编译器编写此代码,这将使其变得更加容易(我不会详细介绍,但给您一个想法):
Also writing this using a precompiler like SASS makes it even easier (I won't go into details, but to give you an idea):
.menu {
display: block;
&__item {
display: inline-block;
line-height: 30px;
width: 100px;
}
&--horizontal {
width: 100%;
height: 30px;
}
&--vertical {
width: 100px;
height: 100%;
}
}
这是一种可扩展的方法,因此可以用于小型项目或大型项目.
It's a methodology that's scalable, so it can be used for either small projects or large projects.
这需要一点时间来适应,因此进行一些研究并在一个小型项目上进行试验将是一个很好的起点.
It takes a bit of getting used to, so doing some research and playing with it on a small scale project would be a good starting point.
这是一个用例,如果您想在实际项目中使用它,请 https://m.alphasights.com/how-we-use-bem-to-modularise-our-css-82a0c39463b0#.2uvxts71f
Here's a use case, if you want to see it in used in a real project https://m.alphasights.com/how-we-use-bem-to-modularise-our-css-82a0c39463b0#.2uvxts71f
希望它会有所帮助:)
这篇关于什么是BEM方法论?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!