@Container queries
@container
queries are a new feature that allow you to query the size of a container. This is useful for creating responsive components that can adapt to the size of their container. This is different from media queries, which query the size of the viewport.
Setting up the HTML
<div class="wrapper">
<div class="card">
card
</div>
<div class="card">
card
</div>
<div class="card">
card
</div>
</div>
Setting up the CSS
.wrapper {
display: flex;
flex-wrap: wrap;
container: test / inline-size;
}
.card {
width: 100%;
background: blue;
padding: 1em;
box-sizing: border-box;
}
@container test (width >= 800px) {
.card {
width: 50%;
}
}
Here we have a wrapper with three cards. The wrapper has a container query that says when the width of the wrapper is greater than 800px, the cards should be 50% width. When the width is less than 800px, the cards should be 100% width.
the container
property is a shorthand for the container-name
and container-type
properties. The container-name property is the name of the container. The container-type
property is type of containment context.
Demo
See the Pen @container by Austin (@theskillwithin) on CodePen.