DEV Community

CSS Layouts: Get Started with Container Queries

Diana Le on October 25, 2023

Welcome to another year of the State of CSS. Like for last year's State of CSS 2022, I will be creating a series of examples and tutorials mentione...
Collapse
 
lexiebkm profile image
Alexander B.K.

To make the target container even clearer, I would add container-name property in the rule like so :

/* Create the container / set the containment context */
.card-wrapper-container {
  container-type: inline-size;
  container-name: anyvalidname;
  /* or using shorthand syntax like the following :
     container: anyvalidname / inline-size;
  */
}

/* Define the container query using @container */
/* The rule below says: find the closest ancestor with a
 containment context 
- in this case "card-wrapper-container" -
and when the width is 560 pixels and above, 
set the grid columns to 2 */
@container anyvalidname (min-width: 560px) {
  .card-wrapper {
    grid-template-columns: repeat(2, 1fr);
  }
}
Enter fullscreen mode Exit fullscreen mode

Actually I am still learning; I am currently still exploring Grid more detail. But when I saw this post, I felt that I wanted to take time to read, because this was relevant to what I was currently learning, including all @ rules which can be useful for my use cases in the future.
My current priority of @ rules is on @media, @supports, @import, @layer and @keyframes.
I haven't been paying attention to this @container yet. But now that you introduce it here, I think I will take time to explore it more as well as the related topics like containment via contain property.
So thank you for introducing another useful @ rule here.

Collapse
 
dianale profile image
Diana Le

Yes, that's a good point about container names. I'm thinking to do a more advanced post about container queries later on after I work with them some more. I haven't used multiple containment contexts yet.

Glad that you're learning these topics!