Using CSS Container Queries involves two main steps: defining a container and then writing container queries to adjust styles based on the size of that container.
Step 1: Define the Container
To apply container queries, first, you need to declare an element as a container. You do this by setting the container-type property. Here’s a simple example:
.container {
container-type: inline-size;
}
This tells the browser to monitor the size of .container in terms of its inline-size (usually the width).
Step 2: Write the Container Query
Next, you can write a container query to style elements based on the size of the container. Here's an example where we change the background color of a .box when the container is at least 400 pixels wide:
@container (min-width: 400px) {
.box {
background-color: lightblue;
font-size: 20px;
}
}
In this example, when the .container element is at least 400 pixels wide, the .box inside it will get a light blue background and larger font size.
Step 3: Put It All Together
Here’s how the HTML and CSS might look in a real-world scenario:
<div class="container">
<div class="box">Resize me!</div>
</div>
And the CSS:
.container {
container-type: inline-size;
padding: 20px;
border: 2px solid black;
}
.box {
background-color: lightgray;
padding: 10px;
}
@container (min-width: 400px) {
.box {
background-color: lightblue;
font-size: 20px;
}
}
As the .container changes size, the styles of the .box will adapt accordingly based on the container’s width, not the browser window.