CSS Naming Conventions that Will Save You Hours of Debugging

Ohans Emmanuel
Jan 16, 2018 · 7 min read

you’ve been there before, haven’t you?

Use Hyphen Delimited Strings

var redBox = document.getElementById('...')
.redBox {
border: 1px solid red;
}
.red-box {
border: 1px solid red;
}
// Correct.some-class {
font-weight: 10em
}
// Wrong.some-class {
fontWeight: 10em
}

The BEM Naming Convention

.nav--secondary {
...
}
.nav__header {
...
}

Explaining BEM to a 5 year Old

It is an award winning image of a stick-man :)
.stick-man {

}

E for Elements

.stick-man__head {}.stick-man__arms {}.stick-man__feet {}

M for Modifiers

.stick-man--blue {}.stick-man--red {}
.stick-man__head--small {}.stick-man__head--big {}

Why Use Naming Conventions?

There are only two hard problems in Computer Science: cache invalidation and naming things — Phil Karlton

CSS Names with JavaScript Hooks

<div class="siteNavigation"></div>
<div class="site-navigation"></div>
//the Javasript codeconst nav = document.querySelector('.siteNavigation')

1. Use js- class names

<div class="site-navigation js-site-navigation"></div>
//the Javasript codeconst nav = document.querySelector('.js-site-navigation')

2. Use the Rel attribute

<link rel="stylesheet" type="text/css" href="main.css">
<div class="site-navigation" rel="js-site-navigation"></div>
const nav = document.querySelector("[rel='js-site-navigation']")

3. Don’t use data attributes

Good use of data attributes. As seen on Twitter

Bonus Tip: Write More CSS Comments

Ready to become Pro?

Seven CSS Secrets you didn’t know about

freeCodeCamp.org

This is no longer updated. Go to https://freecodecamp.org/news instead

Ohans Emmanuel

Written by

I build complex frontends. I teach intricate subjects. https://leanpub.com/reintroducing-react

freeCodeCamp.org

This is no longer updated. Go to https://freecodecamp.org/news instead