Logo

Nesting in CSS without a preprocessor

Categories

Frontend developmentCSSWeb Development
Published at: 2022-01-02

For many years, nested styles in CSS required preprocessors such as Sass or Less. Today, modern CSS supports native nesting, which allows cleaner style organization without an additional compilation layer.

Nesting in CSS

Traditionally, we wrote nested syntax in a preprocessor:

header {
    .heading {
        color: red;
    }
}

This compiles to the following CSS:

header .heading {
    color: red;
}

With native CSS nesting, we can now write:

header {
    & .heading {
        color: red;
    }
}

The & selector references the current parent selector. You can also nest deeper structures when needed:

header {
    & .heading {
        color: red;
        & .sub-heading {
            color: blue;
        }
    }
}