Responsive design just leveled up! If you’re tired of using media queries to tweak every layout, container queries are here to save the day. With container queries, components adapt based on the size of their parent container instead of the entire viewport. Imagine building fully modular components that look perfect in any context—they’ll fit right in whether they’re in a sidebar, main content area, or anywhere else. Sounds great, right?
Let’s dive into a practical, hands-on tutorial to bring container queries to life!
Getting Started: Set Up the HTML
We’ll kick things off with a simple HTML structure. In this example, .wrapper will be our parent container, holding several .card components. The CSS we apply will allow each .card to automatically adjust its look based on the width of .wrapper.
See the Pen Container Queries in CSS by Julius Garcia (@Julius-Garcia-the-bashful) on CodePen.
In this setup, .wrapper becomes the container that drives the responsive styling, while each .card listens to its size. This approach keeps everything flexible and modular, so .card styles adjust perfectly no matter where you place them!
Time for the Magic: Writing CSS with Container Queries
Now, let’s make the CSS magic happen. We’ll use container queries on .wrapper so each .card changes dynamically as .wrapper resizes.
See the Pen Container Queries in CSS by Julius Garcia (@Julius-Garcia-the-bashful) on CodePen.
👓 Breaking Down the CSS
Let’s unpack what’s going on here:
- Container Setup (
.wrapper):container-type: inline-size;tells the browser to treat.wrapperas a query-able container, focusing on its width.container-name: layout-container;names the container, so you can target it with@containerrules.
- Base Styles for
.card:- We give each
.cardbasic padding, a background color, and a smooth transition. This keeps them looking clean on all screen sizes.
- We give each
- Container Queries:
- The first
@container layout-container (min-width: 500px)applies when.wrapperis at least 500px wide, changing the.cardbackground to a light blue and text color to dark blue. - The second query at
min-width: 800pxfurther adapts the.cardstyles, giving them a greenish tint, a larger font, and making them look more prominent.
- The first
See the Pen Container Queries in CSS by Julius Garcia (@Julius-Garcia-the-bashful) on CodePen.
🎉 Wrapping It Up
And that’s it! Resize the browser window to watch each .card automatically adjust as the .wrapper grows and shrinks. Container queries give you a way to design responsive components that are truly modular, allowing for cleaner CSS, fewer media queries, and layouts that look great everywhere.
With this new CSS tool, your components can be flexible, adaptable, and ready for any layout. Try it out, and welcome to the next level of responsive design!