DEV Community

Cover image for Removing complexity with container size queries
moji ///
moji ///

Posted on • Originally published at moji.blog

Removing complexity with container size queries

📦 Container Size Queries in CSS are exceptionally helpful when building dashboards. Especially when they are user configurable. Imagine a scenario where the same component can be placed multiple times, displaying different information and having different column-span settings. Or just being used in the sidebar as well as in the main content area depending on the page.

Here we use the same component in two different places with different column-span. They show us information in different formats:

Try it out by opening it in a new tab and resizing. It is the exact same component. Of course as a simplified version of a real component in a project.

Up until now, with media queries, we could not have solved this easily. Our styling would apply to all instances of the component on the page equally and could not handle sizing dependent on placement. This would require complex classes that get set or removed and would trigger mobile styling earlier on larger uses..

✅ Lets use a container query and also define the container type. Figuring out where to set a container type like container-type: inline-size can be a challenge when creating the component.

Be careful, as you can not put a container query on the same element you apply the container type to.

.item {
  background-color: white;
  border-radius: 6px;
  overflow: hidden;
  box-shadow: var(--shadow-elevation-medium);
  container-type: inline-size;
}

@container (min-width: 400px) {
  .shipping__line {
    flex-wrap: wrap;
    border: 2px solid #f1cffc;
    border-radius: 6px;
    padding: 1rem;
    gap: 1rem;
    text-align: center;
  }
}
Enter fullscreen mode Exit fullscreen mode

Extending this a little bit more we can easily build our multi-use dashboard components – and not worry about device size & adding and removing complex extra classes.

There is also the possiblity to use style queries in addition, to offer even more flexiblity to the user without much effort. Ahmad Shadeed has written a fantastic article on that with quite a lot of use cases and examples.

Have you used container queries already or are planning to?
You can find me on twitter here or on my blog here

Top comments (0)