How container queries work ? 🎁
Back in the day, we only had a way to respond to different sizes in our elements; media-queries.
And that’s perfectly okay, however container queries gives us more flexibility; we can rely on the size of our parent container and not only on the viewport.
Get Alejandro Tinoco Duarte’s stories in your inbox
Join Medium for free to get updates from this writer.
Let’s start with a main container with class ‘container’, which will be our query container, and his children will response to his size.
<div class='container'>
<div class='box'>
<h2>Resize me! 🎁</h2>
</div>
</div>
In our container we need to add two properties:
container-type and container-name (optional).
.container {
container-type: inline-size;
container-name: giftBox;
}There are another properties for style reasons but the only relevant one is the initial width set to 700px.
.container {
container-type: inline-size;
container-name: giftBox;
display: flex;
justify-content: center;
align-items: center;
resize: both;
overflow: auto;
border: 5px solid black;
width: 700px;
}We set a default font-size for our h2 tag.
.box h2 {
font-size: 1em;
}And a size to take when his parent container is at least 700px wide.
@container giftBox (min-width: 700px) {
.box h2 {
font-size: 3em;
}
}Our h2 inside our query container has an initial font-size of 3 em.
But if we make our container smaller (less than 700px wide).
Now the font-size rezises to 1em!
Here is a Playground to play and test container queries with the code that we saw above, happy coding!
References:
- MDN Docs on container queries







