Sub topic 2
Attaching Classes and Pseudo-Classes with `&`
Assume you know CSS selectors, combinators, specificity, and media queries. In native CSS nesting, & is the nesting selector. It represents the complete selector of the outer rule.
Attaching a class or pseudo-class
Put & directly before a class, attribute, or pseudo-class when both parts must match the same element. There is no space between them.
.card {
border: 1px solid #ccc;
padding: 1rem;
&.featured {
border-color: gold;
}
&:hover {
box-shadow: 0 2px 8px rgb(0 0 0 / 20%);
}
&[aria-expanded="true"] {
background: #f5f5f5;
}
&::before {
content: "★";
color: gold;
}
}For example, &.featured becomes .card.featured. It selects one element with both classes. In contrast, .featured without & creates a descendant selector, equivalent to .card .featured.
The same rule applies to pseudo-classes such as :focus-visible, :disabled, and :not(...), and to pseudo-elements such as ::before.
Styling by ancestor context
You can place & at the end of a selector to express an ancestor relationship:
.card {
color: #222;
.dark-theme & {
color: #eee;
background: #222;
}
}This becomes .dark-theme .card. The card is styled only when an ancestor has the dark-theme class. This pattern is useful for themes, page states, and layout contexts.
Nesting conditional at-rules
Conditional at-rules can appear inside a style rule. Their declarations still apply to the parent selector:
.panel {
display: block;
@media (min-width: 40rem) {
display: grid;
grid-template-columns: 1fr 2fr;
}
@supports (container-type: inline-size) {
container-type: inline-size;
}
}The media query changes .panel at wider viewports. The @supports rule applies the declaration only when the browser understands the feature. The same structure works with @container and @layer.
Exercise
What selector does .button { &:disabled { opacity: 0.5; } } produce?
Show answer
It produces .button:disabled, selecting a disabled button itself.