Modern CSS Best Practices

Chapter 2 of 9 · 4 practices · 3 min · 3-question quiz

The cascade, specificity and cascade layers

Most CSS pain comes from styles fighting each other. This chapter covers keeping specificity low and using cascade layers to decide which group of styles wins.

Start: Keep specificity low and flat

4 practices in this chapter

  1. 1Keep specificity low and flatWhen two rules set the same property, the one with higher specificity wins, regardless of where it appears. Codebases that use IDs, long descendant chains and !important end up in an arms race…
  2. 2Use cascade layers to order groups of styles explicitlyCascade layers let you put styles into named groups and decide which group wins, before specificity is even compared. A one class rule in a later layer beats a rule with an ID in an earlier layer.
  3. 3Know the two layer rules that surprise people: unlayered styles and !importantTwo behaviours from the cascade layers spec catch most people out. MDN describes both: 1. Unlayered styles beat all layered styles. For normal declarations, any rule not in a layer wins over every…
  4. 4Scope component styles with a naming convention or @scopeGlobal class names collide. A .title in the card component and a .title in the modal will affect each other as soon as both are on the page.

Check yourself on this chapter

3 questions, right here once you are signed in. Your progress is saved as you read.

Sign up for the quiz