阿里云主机折上折
  • 微信号
Current Site:Index > The BEM naming methodology translates this sentence into English.

The BEM naming methodology translates this sentence into English.

Author:Chuan Chen 阅读数:37169人阅读 分类: CSS

BEM is a popular CSS naming methodology that addresses style conflicts and maintainability issues in front-end development through strict naming conventions. BEM stands for Block, Element, Modifier, and its core idea is to break down the interface into independent modules while clarifying their relationships and states through naming conventions.

Basic Concepts of BEM

The BEM methodology decomposes the user interface into three fundamental parts:

  1. Block: An independent, reusable component, such as a navigation bar, button, or card. Blocks are named using a single word or lowercase letters connected by hyphens.

    .menu {}
    .search-form {}
    
  2. Element: A constituent part of a block that cannot exist independently. Element names are connected to the block name using double underscores __.

    .menu__item {}
    .search-form__input {}
    
  3. Modifier: Represents the state or variant of a block or element. Modifiers are connected to the block or element name using double hyphens --.

    .button--disabled {}
    .menu__item--active {}
    

Detailed Naming Rules of BEM

Block Naming Conventions

Block names should be concise and semantic, avoiding style- or layout-related terms. For example:

/* Recommended */
.alert-box {}
.user-profile {}

/* Not recommended */
.red-box {} /* Avoid color descriptions */
.left-side {} /* Avoid layout descriptions */

Element Nesting Relationships

BEM prohibits reflecting DOM nesting hierarchy in naming. Even if elements are nested deeply in the HTML, naming remains flat:

<!-- HTML structure -->
<div class="card">
  <div class="card__header">
    <h2 class="card__title"></h2>
  </div>
</div>

<!-- Incorrect example -->
.card__header__title {} /* Violates BEM principles */

Use Cases for Modifiers

Modifiers come in two types:

  1. Boolean Modifiers: Indicate the presence or absence of a state, typically without a value.
    .button--active {}
    .accordion--expanded {}
    
  2. Key-Value Modifiers: Describe specific variant characteristics.
    .theme--dark {}
    .size--large {}
    

Practical Examples of BEM

Navigation Component Implementation

<nav class="nav">
  <ul class="nav__list">
    <li class="nav__item nav__item--current">
      <a class="nav__link" href="#">Home</a>
    </li>
    <li class="nav__item">
      <a class="nav__link" href="#">Products</a>
    </li>
  </ul>
</nav>

Corresponding CSS:

.nav {
  background-color: #333;
}
.nav__list {
  display: flex;
  list-style: none;
}
.nav__item {
  padding: 0 1rem;
}
.nav__item--current {
  border-bottom: 2px solid #f00;
}
.nav__link {
  color: white;
  text-decoration: none;
}

Themed Button Component

<button class="btn btn--primary btn--rounded">Submit</button>
<button class="btn btn--secondary btn--large">Cancel</button>

CSS implementation:

.btn {
  border: none;
  padding: 0.5rem 1rem;
  cursor: pointer;
}
.btn--primary {
  background-color: #0066cc;
  color: white;
}
.btn--secondary {
  background-color: #e6e6e6;
}
.btn--rounded {
  border-radius: 1rem;
}
.btn--large {
  padding: 1rem 2rem;
  font-size: 1.2rem;
}

Advanced Techniques in BEM

Mixing Blocks (Mix)

Allows applying styles from multiple blocks to the same DOM element:

<div class="card user-profile"></div>

Define the two independent blocks in CSS:

.card {
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.user-profile {
  background-color: #f5f5f5;
}

Handling Dynamically Generated Class Names

In modern front-end frameworks, BEM can be combined with CSS modules:

// React component example
import styles from './Button.module.css';

function Button({ variant }) {
  return (
    <button className={`${styles.btn} ${styles[`btn--${variant}`]}`}>
      Click me
    </button>
  );
}

Common Misconceptions About BEM

  1. Over-nesting Selectors:

    /* Incorrect example */
    .block .block__element .block__another-element {}
    
    /* Correct approach */
    .block__element {}
    .block__another-element {}
    
  2. Overusing Modifiers:

    /* Incorrect example - should be split into separate blocks */
    .modal--login {}
    .modal--signup {}
    
    /* More reasonable structure */
    .login-form {}
    .signup-form {}
    
  3. Ignoring Block Independence:

    /* Incorrect example - block styles depend on parent container */
    .sidebar .button {}
    
    /* Correct approach - use modifiers */
    .button--sidebar {}
    

Combining BEM with Other Technologies

Integration with SASS/LESS

Use preprocessors to reduce repetitive input:

.card {
  &__header {
    padding: 1rem;
  }
  &__title {
    font-size: 1.2rem;
  }
  &--featured {
    border: 2px solid gold;
  }
}

Integration with CSS-in-JS Solutions

Apply BEM principles in styled-components:

const StyledButton = styled.button`
  padding: 0.5rem;
  &--primary {
    background: blue;
  }
  &--large {
    font-size: 1.2rem;
  }
`;

Variants and Extensions of BEM

Namespaced Variants of BEM

Some teams add prefixes to distinguish between different types of blocks:

.c-card {} /* Component */
.l-grid {} /* Layout */
.u-hidden {} /* Utility class */

Combining BEM with ITCSS

Integrate BEM architecture into a layered CSS methodology:

settings/    # Global variables
tools/       # Mixins and functions
generic/     # Resets and base styles
elements/    # HTML element styles
objects/     # Abstract design patterns
components/  # BEM blocks
utilities/   # Helper classes

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.