Cascading Style Sheets
Two things in CSS help determine which style(s) an element inherits.
Source: https://stuffandnonsense.co.uk/archives/images/specificitywars-05v2.jpg
#creature.equine.unicorn .body mane hair { color: blue; }
#creature.equine.horse .body mane hair { color: brown; }
#creature.equine.zebra .body mane hair { color: black; }
#creature hair { color: red !important; }
#creature.horse hair { color: green !important; }
HTML
CSS
// relatively simple selector
.horse mane {
color: brown;
}
// complex selector
creature#unicorn.equine.unicorn mane {
color: black;
}
The client says hey, all horses and unicorns need white manes.
.equine mane {
color: white !important; :(
}
See the Pen BEM - Holy Selectors Batman by WebAdvanced (@WebAdvanced) on CodePen.
These can only be overwritten with !important
(Also, just don't use inline CSS.)
Block
Element
Modifier
// wrong
div.news-showcase { ... }
#news.news-showcase { ... }
// correct
.news-showcase { ... }
// wrong
.homepage .news-showcase { ... }
// correct
.news-showcase { ... }
.news-showcase__item { }
// wrong
div.news-showcase__item { }
// wrong
.news-showcase .news-showcase__item { }
// correct
.news-showcase__item { }
.news-showcase--full-width { }
.news-showcase__item--large { }
.news-showcase__item--large .news-showcase__heading { } // headings inside large showcase item
//HTML
Watch Video
//JS
$('.js--open-modal').magnificPopup();
//No CSS!
See the Pen BEM Presentation - HTML by WebAdvanced (@WebAdvanced) on CodePen.
See the Pen BEM Presentation - CSS by WebAdvanced (@WebAdvanced) on CodePen.
You can group BEM blocks with their elements and modifiers into a tidy package using SASS or LESS.
// The SCSS
.news-showcase {
...
&__item {
...
&--large {
...
.news-showcase__heading {
...
}
}
}
&__heading {
...
}
}
// The Generated CSS
.news-showcase { ... }
.news-showcase__item { ... }
.news-showcase__item--large { ... }
.news-showcase__item--large .news-showcase__heading { ... }
.news-showcase__heading { ... }
Let's try to avoid this!