CSS Naming Convention

Naming conventions: CSS Best Practices, Part 1

CSS is often mistaken for something easy in Web Development, but it requires quite a bit of skill to master. Even after almost 10 years of working with CSS, I’m learning new approaches, handy tips, and tricks to create even leaner code.

Something I often see overlooked by up-and-coming front-end developers, is consistent naming conventions in their code and in their CSS. That’s why I today will cover my approach to naming CSS classes and IDs.  

Naming conventions

Using consistent naming conventions in your CSS code has several benefits, including:

  1. Improving readability
    Consistent naming conventions make it easier for other developers (and even yourself) to read and understand your code, reducing the likelihood of errors or confusion.
  2. Encouraging modular design
    Naming conventions like BEM promote modular design, which makes your code easier to maintain and update in the future.
  3. Reducing conflicts
    Consistent naming conventions reduce the likelihood of naming conflicts between different CSS styles, making it easier to debug and update your code.

BEM (Block, Element, Modifier)

BEM is a popular naming convention for CSS that is widely used by developers. The naming convention is a system for naming classes in a way that promotes modularity and consistency. Here’s a brief explanation of each part of the BEM naming convention:

  • Block
    A standalone component or “block” can be reused across your website. Examples of blocks might include a navigation menu, a carousel, or a modal dialog box. Block names should be descriptive and unique, and should be prefixed with the block name, such as nav, carousel, or modal.
  • Element
    A part of a block that has a specific function. Examples of elements might include a link within a navigation menu, a slide within a carousel, or a close button within a modal. Element names should be prefixed with the block name, followed by two underscores, such as nav__link, carousel__slide, or modal__close.
  • Modifier
    A variation of a block or element that changes its appearance or behaviour. Examples of modifiers might include a disabled button, a highlighted link, or a full-width modal. Modifier names should be prefixed with the block or element name, followed by two hyphens. F.e. button–disabled, nav__link–active, or modal–fullwidth.

Using BEM as a naming convention for your CSS code can make your code more readable, maintainable, and modular. The system also makes it easier to collaborate with other developers and avoid naming conflicts.

More CSS best practices