Classes vs. IDs

  • Use IDs as JS hooks or as fragments identifiers in our page.
  • Style with classes first. IDs are heavy on specificity, that’s why classes are more flexible for styling.
  • Avoid using the same class or ID for styling and JavaScript. Keep those layers separate!
  • It’s best to prefix JavaScript classes with js-, they’ll be easily identied as JS hooks. This will decouple presentational classes from functional classes.

Specificity Degrees

  1. Important!
  2. Inline
  3. IDs
  4. Classes
  5. Elements

Examples

h1 
//Specificity: 0001

.active
//Specificity: 0010

#nav .active
//Specificity: 0110

#nav li.active
//Specificity: 0111

ul#nav li.active
//Specificity: 0112
<li styles="color: blue;">
//Specificity: 1000

Avoid These!

Don’t rely on parent selectors!

They lower the specificity of child elements. Use namespaces instead to extend a class selector and keep components modular.

.sidebar {
  ...
}
.sidebar .title {
  ...
}

A better practice is as follows:

.sidebar {
  ...
}
.sidebar-title {
  ...
}

Very similar to subclass name modules in SMACSS.

Don’t Rely on Tag Selectors

They’re not reusable, can be easily overridden, and make our CSS architecture more fragile.

Avoid !important Declarations

It breaks the CSS cascade. Do not use them unless absolutely necessary!

Avoid Universal Selector

Why you should not use the universal selector *

  • No control over which elements are reset
  • Inheritance is lost in CSS values
  • Affects page load – browser has to run through every page element to apply properties