Ask any question about CSS here... and get an instant response.
How can I use container queries to adjust a layout when a parent div changes size?
Asked on Nov 21, 2025
Answer
Container queries allow you to apply styles to elements based on the size of their container rather than the viewport. This is useful for creating responsive designs that adapt to the size of their parent elements.
<!-- BEGIN COPY / PASTE -->
<style>
.container {
container-type: inline-size;
width: 100%;
max-width: 600px;
margin: 0 auto;
padding: 20px;
background-color: lightgray;
}
.item {
background-color: lightblue;
padding: 10px;
margin: 10px 0;
}
@container (min-width: 400px) {
.item {
background-color: lightcoral;
font-size: 1.2em;
}
}
</style>
<div class="container">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
</div>
<!-- END COPY / PASTE -->Additional Comment:
- Container queries use the "container-type" property to define a container that can be queried.
- Use "@container" followed by conditions like "(min-width: 400px)" to apply styles when the container meets those conditions.
- This example changes the background color and font size of ".item" elements when the ".container" is at least 400px wide.
- Ensure your browser supports container queries, as this is a relatively new CSS feature.
Recommended Links:
