How to do Native CSS Nesting now

Toys Samurai
1 min readSep 28, 2022

No, true native CSS nesting is currently a work in progress. However, there is currently a workaround to natively nest CSS style rules. Enter Container Queries. Without getting into the specifics of how Container Queries function (Google it; many people can explain it better than I can), this is how you can nest CSS style rules right now:

<div class="my-container">
<div class="some-content">ABC</div>
</div>
<div class="my-other-container">
<div class="some-content">ABC</div>
</div>

And, here’s the CSS:

.my-container {
container-type: inline-size;
container-name: my-container;
}
.some-content {
background-color: #cccccc;
margin: 10px auto;
padding: 10px;
width: 50px;
height: 50px;
text-align: center;
}
@container my-container (min-width: 0px) {
.some-content {
background-color: #444444;
color: #ffffff;
text-align: center;
font-size: 30px;
margin: 20px auto;
width: 300px;
height: 300px;
padding: 20px;
}
}

The trick here is to provide the query a condition so that it is always activated. Here is a link where you can test it out: https://codepen.io/toyssamurai/pen/gOzvbMV

Currently, it is supported (partially) by Chrome & Edge 105+, as well as Safari 16+ ( https://caniuse.com/css-container-queries ).

CSS purists would disagree, arguing that this isn’t the purpose of container inquiries and that your rules might infect other “true” container queries. However, you are not technically lying. The rendering engine is doing exactly what it should be doing when it presents specific default rules in an unnecessary container query. I’ll categorize it as a “float” trick type of CSS trick.

--

--