Welcome back to CodeYourCraft! Today, we're diving into the world of CSS Container Queries, a game-changer in responsive web design.
Container Queries allow you to style a container based on its own size, and the sizes of its children, rather than the viewport. This means you can tailor your designs to specific content, making your layouts more efficient and adaptable.
First, let's make sure your browser supports Container Queries. As of now, Chrome 90+, Firefox 90+, Edge 90+, and Safari 15.3+ support Container Queries.
To use Container Queries, you'll need to use the @container rule. Here's a simple example:
@container medium-up {
/* Styles applied when the container is at least medium size and all its children are included */
}Unlike media queries, Container Queries don't require specific breakpoints. Instead, they use relative terms:
small: The container is smaller than its children.medium: The container is larger than its children, but no larger than twice the size of its children.large: The container is larger than twice the size of its children.You can nest Container Queries to create more complex layouts. Here's an example:
@container medium-up {
/* Styles for the container and its children */
@container small {
/* Styles applied when the nested container is smaller than its children */
}
}Let's create a simple grid layout that adjusts based on the container size:
<div class="container">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
</div>.container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
gap: 10px;
}
@container medium-up {
.container {
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
}
}What does `medium-up` in the `@container` rule mean?
That's it for today! We hope you enjoyed learning about CSS Container Queries. Stay tuned for more exciting topics. Happy coding! ๐ฉโ๐ป๐จโ๐ป๐ป๐ป