CodeBlanks Logo Icon CodeBlanks

What is CSS nesting?

CSS course · Expert · Lesson 43/53

Learn the native CSS nesting syntax.

What is CSS nesting?

CSS nesting places one selector inside the curly braces of another. The browser treats the inner block as a descendant of the outer selector. So .card { h2 { color: navy; } } means the same as .card h2 { color: navy; }.

This structure may feel familiar from preprocessors like Sass; it now works in plain CSS. An element's own styles, its children and its pseudo-classes sit in a single block; the stylesheet mirrors the HTML structure.

Why use nesting?

Without nesting, a component's styles scatter across the file: .card, .card h2, .card p each on its own line. With nesting they all sit inside the .card block.

The stylesheet mirrors the HTML structure and stays easier to maintain. BEM names like .card__title from Sass are less needed; .card { .title { } } is enough.

Descendant combinator by default

When you nest, the browser joins the inner selector to the outer one with the descendant combinator. So nav { a { color: navy; } } becomes nav a { color: navy; }; it catches every a inside nav.

The inner element does not have to be a direct child; a deeper descendant also matches. The > combinator for direct children is covered in a later lesson.

Exercise Set a color for nested p

Add a p selector inside the .card block and assign color: navy. The outer block already exists; write only the inner p block.

Show example solution
navy; in it.
Example solution:
/* add p inside .card */
.card {
  padding: 1rem;
  p {
    color: navy;
  }
}

Test yourself

  1. Which snippet shows valid nesting?

    • .card { color: navy; }
    • .card { h2 { color: navy; } }
    • .card h2; { color: navy; }
    • card h2 { color: navy; }
    Show answer

    .card { h2 { color: navy; } } — Correct. The h2 selector sits in its own curly block inside .card; the browser resolves it as .card h2.

  2. Write the inner selector

    .card {
      ____ {
        color: navy;
      }
    }
    Show answer
    .card {
      h2 {
        color: navy;
      }
    }

All lessons in Expert