9 Modular CSS and scope

 

This chapter covers

  • Organizing CSS into reusable modules
  • Preventing escalating selector specificity
  • Common naming conventions for CSS organization
  • Using @scope for better control of the cascade
  • Using a pattern library to document your modules

When you make changes to an existing stylesheet, those changes can affect any number of elements on any number of pages across your site. Here’s an old joke: two CSS properties walk into a bar; a barstool in a different bar falls over. So how do you ensure your change applies to all the places you want updated? And how do you know your change won’t affect elements you don’t want changed?

In the previous chapter, we looked at layers, which are the first step in controlling the priority of the various styles on the page. I recommended defining several layers on your page. The largest of these, the modules layer, is where the bulk of your styles should reside. This chapter is about organizing that layer into manageable, modular pieces of code.

9.1 Defining modules

Modular CSS means breaking the page up into its component parts. These parts should be reusable in multiple contexts, and they shouldn’t directly depend on one another. The end goal is that changes to one part of your CSS will not produce unexpected effects in another.

9.1.1 Modules and global styles

9.1.2 A simple module

9.1.3 Variations of a module

9.1.4 Modules with multiple elements

9.2 Modules composed into larger structures

9.2.1 Dividing multiple responsibilities among modules

9.2.2 Naming modules

9.3 CSS scope

9.3.1 Scope proximity

9.3.2 Scoping limit

9.3.3 Implicit scope

9.3.4 Scope and layers

9.4 Pattern libraries

9.4.1 Using a CSS-first workflow

9.4.2 Refactoring and breaking changes

Summary