BEM(block、element、modifier)是一种基于组件的Web开发方法。其背后的想法是将用户界面划分为独立的块。这使得界面开发变得简单和快速,即使是在复杂的用户界面中,它也允许在不复制和粘贴的情况下重用现有代码。-----源于百度翻译(-_-)
## 概念
* Block
块,可重用的功能独立的页面组件。
* element
块的子元素,不能单独使用。
* modifier
定义块或元素的外观、状态或行为
**元素有两个优点**:
* 你可以让 CSS 的优先级保持相对扁平。
* 你能立即知道哪些是子元素。
## 样式分割原则
作者在提到 Dividing the code into parts,样式分割的时候,提到几个原则
1. [Single responsibility principle](https://en.bem.info/methodology/css/#single-responsibility-principle)
单一职责
2. [Open/closed principle](https://en.bem.info/methodology/css/#openclosed-principle)
开闭原则,修改关闭,扩展开放
3. [DRY](https://en.bem.info/methodology/css/#dry) "don't repeat yourself
不重复
4. [Composition instead of inheritance](https://en.bem.info/methodology/css/#composition-instead-of-inheritance)
组合优先
## 实施原则
* 抛开DOM模型,学习创建块。
* 不要使用ID选择器或标记选择器。
* 最小化嵌套选择器的数量。
* 使用CSS类命名约定以避免名称冲突,并尽可能使选择器名称见名之意。
* 使用块、元素和修饰符。
* 将块的CSS属性移动到修饰符(如果它们可能被更改)。
* 组合使用。
* 将代码划分为小的独立部分,以便于使用单独的块。
* 复用块。
一些注意事项
1. element 不能嵌套element, 例如:`block__elem1__elem2`.
~~~css
<!--
Incorrect. The structure of the full element name doesn't follow the pattern:
`block-name__element-name`
-->
<form class="search-form">
<div class="search-form__content">
<!-- Recommended: `search-form__input` or `search-form__content-input` -->
<input class="search-form__content__input">
<!-- Recommended: `search-form__button` or `search-form__content-button` -->
<button class="search-form__content__button">Search</button>
</div>
</form>
~~~
2. modifier 前面不一定有element
* `block-name_modifier-name`
* `block-name__element-name_modifier-name`
3. modifier可以是键值对
* `block-name_modifier-name_modifier-value`
* `block-name__element-name_modifier-name_modifier-value`
~~~css
<form class="search-form search-form_theme_islands">
<input class="search-form__input">
<!-- The `button` element has the `size` modifier with the value `m` -->
<button class="search-form__button search-form__button_size_m">Search</button>
</form>
~~~
4. Mix。可以在同一个DOM节点上使用不同的BEM实体。
~~~css
<!-- `header` block -->
<div class="header">
<!--
The `search-form` block is mixed with the `search-form` element
from the `header` block
-->
<div class="search-form header__search-form"></div>
</div>
~~~
5.组合选择器
BEM方法不建议使用组合选择器。与单个选择器相比,组合选择器(如.button.button_theme_islands)具有更高的CSS特异性,这使得重新定义它们更加困难.
建议使用简单的选择器
~~~
.button_active {}
.button {}
~~~
> [BEM](https://en.bem.info/)
[CSS命名规范——BEM思想(非常赞的规范)](https://www.cnblogs.com/dujishi/p/5862911.html)
[BEM 入门](https://www.w3cplus.com/blog/tags/325.html)
[How to properly set an element's scope using BEM?](https://stackoverflow.com/questions/27894664/how-to-properly-set-an-elements-scope-using-bem)
[关于BEM中常见的十个问题以及如何避免](https://www.w3cplus.com/css/battling-bem-extended-edition-common-problems-and-how-to-avoid-them.html)
[More Transparent UI Code with Namespaces](https://csswizardry.com/2015/03/more-transparent-ui-code-with-namespaces/)
