Speaking of container queries, it’s time for a pop quiz (don’t run from the grind bb 😘).
How would you target containers that are smaller than 400px?
How would you target containers that are smaller than 400px?
By using the @container at-rule you can easily apply styles to any container that matches the query.
.banner {
/* some banner styles */
}
@container (width < 400px) {
.banner {
/* apply some styles here */
}
}
The example above applies to all containers, but if you want even more fine tuned control over what elements are selected, you can use named container contexts.
.banner-container {
container-type: inline-size;
container-name: banner; /* apply named container context */
}
@container banner (width < 400px) {
.banner {
/* apply some styles here */
}
}
Container queries can also evaluate the computed styles of a container element 🤯 (note: this part of the spec isn’t fully supported). This makes it possible to do some wild stuff.
@container style(color: blue) {
* {
color: red;
}
}
It’s a lot to take in, but container queries are truly a game changer for component based web design. If you need a little more inspiration check out Ahmad Shadeed’s container query examples.