Nested CSS

by

I was watching a Kevin Powell video on CSS the other day and he mentioned that modern browsers (which, unless you're using Internet Explorer or Safari, is every browser, since they're all "evergreen" these days) supported nested CSS rules. (And strictly speaking Safari is "quasi evergreen," since it gets frequent updates, they're just installed in the operating system's updates, not directly via Safari.) I knew how to use nested CSS rules with preprocessors like Sass/SCSS, but had no idea they were supported natively! NICE!

So, here are some of my notes on the topic.

Basic Nesting

.parent {
    color: blue;
    
    .child {
        color: red;
    }
}

Compiles to:

.parent {
    color: blue;
}
.parent .child {
    color: red;
}

Multiple Levels


.grandparent {
    .parent {
        .child {
            color: red;
        }
    }
}

Using & (Parent Selector)

.button {
    color: blue;
    
    &:hover {
        color: red;
    }
    
    &.active {
        color: green;
    }
    
    &-primary {
        background: gold;
    }
}

compiles to:

.button { color: blue; }
.button:hover { color: red; }
.button.active { color: green; }
.button-primary { background: gold; }

Combining with Media Queries

.sidebar {
    width: 300px;
    
    @media (max-width: 768px) {
        & {
            width: 100%;
        }
    }
}

Nesting Pseudo-classes and Elements

.link {
    color: blue;
    
    &:hover {
        color: red;
    }
    
    &::before {
        content: "→";
    }
}

Multiple Selectors

.heading, .title {
    font-weight: bold;
    
    & span {
        color: red;
    }
}

Compiles to:

.heading, .title { font-weight: bold; }
.heading span, .title span { color: red; }

Direct Child Selector

.parent {
    > .child {
        /* Only direct children */
        color: blue;
    }
}

Important Notes:

This is amazing. As with all things tho, some caveats:

  • don't nest too deely, lest you end up with something too difficult to maintain or use.
  • Always test. Remember this is a new feature and not supported by all browsers. All the major browsers, sure, but not all of them.

More posts

Comments powered by Talkyard.