Sub topic 1
Writing a Rule Inside a Rule
Prerequisites
This chapter assumes you know CSS selectors, combinators, cascade, specificity, and media queries. Native CSS nesting lets you place related rules inside a parent rule without using Sass or another preprocessor.
Writing a rule inside a rule
A nested rule is scoped to the selector that contains it. This example styles .card and then its descendant .title:
.card {
padding: 1rem;
border: 1px solid #ccc;
& .title {
font-weight: 600;
}
}The nested rule is equivalent to:
.card .title {
font-weight: 600;
}Nesting keeps related styles together, but the browser still evaluates the resulting selectors through the normal cascade.
The `&` nesting selector
The & represents the parent selector. Use it when you need to attach something directly to the parent, such as a class or pseudo-class:
.button {
background: steelblue;
color: white;
&:hover {
background: navy;
}
&.is-disabled {
opacity: 0.5;
}
}These rules become .button:hover and .button.is-disabled. The & prevents a descendant relationship.
When you can leave out the `&`
For a descendant selector, modern native nesting allows you to omit &:
.nav {
display: flex;
a {
padding: 0.5rem;
}
}This means .nav a. Keeping & can make the relationship clearer, especially in code that must be read by people familiar with older nesting syntax.
> callout note > Use & for compound selectors and states. Use an unprefixed selector for a descendant. Do not write .button .is-disabled when you mean the same element has both classes.
Child and sibling combinators
A nested selector can begin with a combinator. The combinator describes the relationship to the parent:
.list {
display: grid;
> li {
list-style: none;
}
+ .list {
margin-top: 1rem;
}
~ .help {
color: #666;
}
}These become .list > li, .list + .list, and .list ~ .help.
Exercise
What selector does .panel { > button { color: red; } } produce?
Show answer
.panel > button.