Skip to content

CSS Nesting

Excerpted from MDN Web Docs "Using CSS nesting":

The CSS nesting module allows you to write your stylesheets so that they are easier to read, more modular, and more maintainable. As you are not constantly repeating selectors, the file size can also be reduced.

You can use CSS nesting to create child selectors of a parent, which in turn can be used to target child elements of specific parents.

While CSS nesting may not be appropriate for all situations, one notable benefit is that the structure more closely resembles the corresponding HTML, where child tags/selectors are nested within parent tags/selectors.

See the Pen CSS Nesting 1 (IMS322 Docs) by Eric Sheffield (@ersheff) on CodePen.

It can also help alleviate the complexity of creating multiple classes, provided that the heirarchy of your document structure is not too complicated. In the example below, a class is only needed for the parent <div>, since the color change will only apply to <p> elements that are children of the dark-bg class.

See the Pen CSS Nesting 2 (IMS322 Docs) by Eric Sheffield (@ersheff) on CodePen.