Back to blog

My favorite naming convention for CSS classes

Topics: cssยทarchitecture

Share on

Having a solid naming convention for your project (and enforcing it on every code review) is important for helping the cooperation within a project as well as its maintainability. Good conventions usually helps the developers to create better markup structured into reusable components and makes them understand the code intentions more quickly.

In this article I'm going to show the fundamentals behind a good naming convention and present you with the one I use.

If you already know the basics of CSS Naming Conventions (e.g. BEM), you can skip to the next section.

Fundamentals

The more popular conventions always divide the class name into 3 parts:

Class names will be composed of a component. If needed, an element will be added. Then, optionally, followed by one or more modifiers.

It is perfectly acceptable as well to have a modifier applied directly to a block, skipping the element completely.

Components

Components are structures in your HTML that groups other components or other elements. They usually don't have functionality by themselves, serving as wrappers and styling hooks.

These include modals, panels, widgets, headers, or any form of section in your page.

Simpler items, like buttons or inputs, can be considered either components or elements depending on their function and hierarchy in the code.

Elements

Any item that cannot serve as wrappers to other elements, is forcibly an element.

For example, titles, paragraphs, icons, or anything that needs a parent to make sense (e.g. A title element needs to be a title of something else, like a description title, or page title).

Modifiers

A modifier class can be a temporary state or a permanent variation of a component or element.

Keywords like opened, error, active are usually appended to the class names to represent modifications in style.

Popular Conventions

Here are the currently most popular naming conventions.

Our Suggestion

We can always create our own convention, mixing and matching whatever we want.

The one I prefer and use often goes like this:

/* Camel case,
   hyphens for elements,
   underscore for modifiers */

.blockName-elemName_modName_modVal

Best naming convention ever!

Some examples of this convention would be:

.header
.header-title
.header-rightPanel
.homeCarousel-movieImage_large
.menuDropdown_opened_warning
.menu_opened

Some examples

I like this convention because it's very readable on smaller classes, and is still not too ugly if you need longer classes by avoiding using too much underlines and hifens.

What about you? Which convention do you prefer and why?

Share on

What's your favorite naming convention. Let everyone know on the comment section below:

Sign in with your github account to be able to comment.