CSS’s class naming convention.

Seong-Am Kim
3 min readDec 23, 2021
Photo by Kelly Sikkema on Unsplash

Preface

We give the class name for CSS. Different people have different ways of naming Class, which can confuse the reader.

We need to name the class in a unified way to increase the readability of the code.

CSS has many methodologies. Among them, we will look at how to name Class according to BEM.

https://2020.stateofcss.com/en-US/technologies/methodologies/

BEM is divided into three categories.

  1. Block
  2. Element
  3. Modifier

1. Block

A functionally independent page component that can be reused.

In other words, we talk about components.

https://www.smashingmagazine.com/2012/04/a-new-front-end-methodology-bem/

Features

- The class is named according to the purpose, not how it looks.

Nesting

  • Blocks can be nested in each other.
  • You can have any number of nesting levels.

Rules

  • Use ‘-’ to connect names to each other.
  • For the outermost block, match the component name.
.└──── components           └── edit-text.svelte

2. Element

A composite part of a block that can’t be used separately from it.

An element is a part of a block that performs a certain function.

https://www.smashingmagazine.com/2012/04/a-new-front-end-methodology-bem/

Features

  • The element name is separated from the block name with a double underscore (__).

Nesting

Elements can be nested inside each other.

The block name defines the namespace, which guarantees that the elements are dependent on the block (block__elem).

3. Modifier

An entity that defines the appearance, state, or behavior of a block or element.

https://www.smashingmagazine.com/2012/04/a-new-front-end-methodology-bem/

Features

  • Flags on blocks or elements. Use them to change appearance, behavior or state.
  • The modifier name is separated from the block or element name by two dashes ( — ).
  • A modifier can’t be used alone

Pros and cons

Pros

  • The style structure can be grasped at a glance.
  • The range can be inferred only by the class name.
  • It is easy to collaborate.

Cons

  • When working with Javascript, the code becomes lengthy.
document.getElementsByClassName("block-name__element-name — modifier")
  • It’s hard to choose a double click.

Hyphen and underbar are mixed, so there is a problem that you can’t choose the class name at once by double-click.

--

--