Naming Conventions and Modularity-en

CSS Naming Conventions and Modularity

There are only two hard problems in Computer Science: cache invalidation and naming things — Phil Karlton.
Teams have different approaches to writing CSS selectors. Some teams use hyphen delimiters, while others prefer to use the more structured naming convention called BEM.
Generally, there are 3 problems that CSS naming conventions try to solve:
To know what a selector does, just by looking at its name To have an idea of where a selector can be used, just by looking at it To know the relationships between class names, just by looking at them

Plain CSS Naming Conventions

Using hyphen delimiters

In JavaScript, we prefer writing variables in camel case:
1
var redBox = document.getElementById('...');
Copied!
However, camelCase isn't well-suited to CSS, it is consistent with the CSS property names.
1
// Correct
2
.some-class {
3
font-weight: 10em;
4
}
5
// Wrong
6
.some-class {
7
fontweight: 10em;
8
}
Copied!
So, we should use standard CSS naming convention rather than camelCase:
1
// Bad
2
.redBox {
3
border: 1px solid red;
4
}
5
6
// Good
7
.red-box {
8
border: 1px solid red;
9
}
Copied!
In JavaScript, we prefer writing variables in camel case:
1
var redBox = document.getElementById('...');
Copied!
However, camelCase isn't well-suited to CSS, it is consistent with the CSS property names.
1
// Correct
2
.some-class {
3
font-weight: 10em;
4
}
5
// Wrong
6
.some-class {
7
fontweight: 10em;
8
}
Copied!
So, we should use standard CSS naming convention rather than camelCase:
1
// Bad
2
.redBox {
3
border: 1px solid red;
4
}
5
6
// Good
7
.red-box {
8
border: 1px solid red;
9
}
Copied!

BEM

1
.nav--secondary {
2
...;
3
}
4
.nav__header {
5
...;
6
}
Copied!
Naming things correctly in CSS will make your code easier to read and maintain.
If you choose to use the BEM naming convention, it will become easier to see the relationship between your design components/blocks just by looking at the markup.

SCSS

Last modified 2yr ago