In case you missed it, native support for nesting has been introduced in CSS for all major browsers! Nesting, which is a popular feature in preprocessors like Sass, has been one of the main reasons to continue using preprocessors. However, with native support, it may soon be time to consider dropping a preprocessor altogether.
Nested selectors work in a similar way to Sass. For example, if we have the following markup:
“`html
Child level 1
Child level 2
“`
We can style the nested `
“`css
div {
background: lightblue;
& div {
background: pink;
}
}
“`
We can also use nesting for combinators. In this example using the adjacent sibling combinator, a `
` that is a direct child of a `
“`css
div {
background: lightblue;
& + div {
background: lavender;
}
& > p {
background: lemonchiffon;
}
}
“`
Compound selectors require the use of the `&` operator. In this example, a `
“`css
div {
background: lightblue;
&.featured {
background: turquoise;
}
}
“`
Appending the `&` after the selector reverses the context. If a `
“`css
div {
.featured & {
background: orange;
}
}
“`
Unlike in Sass, selectors cannot be concatenated in native CSS nesting. However, we can combine selectors, although this increases specificity:
“`css
.featured {
&.featured–large {
font-size: 1.4rem;
}
}
“`
We can also nest media queries, container queries, and other `@`-rules:
“`css
div {
@media (min-width: 600px) {
display: flex;
}
}
“`
Nesting can make our code more readable and maintainable, especially when it comes to media queries. However, it is recommended to avoid nesting more than three levels deep. There may also be some performance concerns, as nested selectors need to be parsed by the browser. It is worth considering the use of a PostCSS polyfill for older browsers that do not support CSS nesting.
Overall, native CSS nesting provides a powerful and convenient way to write more organized and efficient stylesheets.
Source link