Wednesday, November 16, 2022

container queries for dummies, the complete idiot's guide to moving beyond media queries

So a lot of sites use CSS media queries to switch between mobile and desktop looks, but sometimes you're more concerned about how much room your widget actually has to work with, rather than what the device itself is.

Enter "Container Queries" - fairly wide support but caniuse points out Firefox is lagging (elsewhere claimed its under way)

I found the MDN pages on container-queries a bit confusing, though (especially how it uses "container" both for a class name even though it's part of the "@container" syntax...(

If you had a media query like 

@media (max-width: 600px) {
  /* … */
}

You might try to replace it with 

@container (max-width: 600px){
/* … */
}

The catch is: some ancestor of the content you are actually concerned about resizing has to act as a "containment context"  - some element with the css property 
 container-type: inline-size;
(inline-size is basically width; block-size could be used for height, or size for both. But I think nine times out of ten you're looking for inline-size there)

Here is a minimalist example codepen I made. Ignore the border and padding I put in for reference...  Ignoring the ugly colors and the border and padding for the wrappers... it demonstrates how the context element can have its own width or be constrained by its own parent, etc.

PS Remember the "_____ for Dummies" books? They started with DOS for Dummies... probably it would have been kinder if the title was "for complete newbies" or "with few assumptions about what you already know", but then the alliteration wouldn't have worked...

No comments:

Post a Comment