CSS规范 BEM

304 阅读2分钟

这是我参与11月更文挑战的第29天,活动详情查看:2021最后一次更文挑战

前言

CSS规范知道多少,一起了解一下BEM规范。

BEM

BEM(block、element、modifier)是一种基于组件的Web开发方法。其背后的想法是将用户界面划分为独立的块。这使得界面开发变得简单和快速,即使是在复杂的用户界面中,它也允许在不复制和粘贴的情况下重用现有代码。

概念

  • Block
    块,可重用的功能独立的页面组件。
  • element
    块的子元素,不能单独使用。
  • modifier
    定义块或元素的外观、状态或行为

元素有两个优点

  • 你可以让 CSS 的优先级保持相对扁平。
  • 你能立即知道哪些是子元素。

样式分割原则

作者在提到 Dividing the code into parts,样式分割的时候,提到几个原则

  1. Single responsibility principle
    单一职责
  2. Open/closed principle
    开闭原则,修改关闭,扩展开放
  3. DRY "don't repeat yourself
    不重复
  4. Composition instead of inheritance
    组合优先

实施原则

  • 抛开DOM模型,学习创建块。
  • 不要使用ID选择器或标记选择器。
  • 最小化嵌套选择器的数量。
  • 使用CSS类命名约定以避免名称冲突,并尽可能使选择器名称见名之意。
  • 使用块、元素和修饰符。
  • 将块的CSS属性移动到修饰符(如果它们可能被更改)。
  • 组合使用。
  • 将代码划分为小的独立部分,以便于使用单独的块。
  • 复用块。

一些注意事项

  1. element 不能嵌套element, 例如:block__elem1__elem2.
<!--
    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>
  1. modifier 前面不一定有element
  • block-name_modifier-name
  • block-name__element-name_modifier-name
  1. modifier可以是键值对
  • block-name_modifier-name_modifier-value
  • block-name__element-name_modifier-name_modifier-value
<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>
  1. Mix。可以在同一个DOM节点上使用不同的BEM实体。
<!-- `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
CSS命名规范——BEM思想(非常赞的规范)
BEM 入门
How to properly set an element's scope using BEM?
关于BEM中常见的十个问题以及如何避免
More Transparent UI Code with Namespaces