惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
SegmentFault 最新的问题
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
B
Blog RSS Feed
Y
Y Combinator Blog
T
Tailwind CSS Blog
博客园 - 三生石上(FineUI控件)
J
Java Code Geeks
Stack Overflow Blog
Stack Overflow Blog
aimingoo的专栏
aimingoo的专栏
Jina AI
Jina AI
The GitHub Blog
The GitHub Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
A
About on SuperTechFans
H
Hackread – Cybersecurity News, Data Breaches, AI and More
D
Docker
酷 壳 – CoolShell
酷 壳 – CoolShell
C
Check Point Blog
M
MIT News - Artificial intelligence
Last Week in AI
Last Week in AI
V
V2EX
腾讯CDC
F
Fortinet All Blogs
博客园 - 叶小钗
T
The Blog of Author Tim Ferriss

Max Böck

Faster Horses A year in review: 2024 Going Buildless Live CMS Previews with Sanity and Eleventy Upgrading to Eleventy v3 Old Dogs, new CSS Tricks A year in review: 2023 7 Reasons why I don't write The IndieWeb for Everyone Make Free Stuff Container Queries in Web Components Asset Pipelines in Eleventy Medium-Style Share Highlights in Eleventy Space Jam Webmention Analytics Making Persistent Build Folders in Netlify A year in review: 2020 Whimsical Website Club The Return of the 90s Web Human Code Color Theme Switcher Eleventy Résumé Builder The Emergency Website Kit Making a Gigposter A year in review: 2019 Webclerks Conference Roads IndieWeb Link Sharing Good Enough The CSS Mindset
Media Queries in Times of @container
Max Böck · 2021-06-11 · via Max Böck

With container queries now on the horizon - will we need media queries at all? Is there a future where we build responsive interfaces completely without them?

Ethan, who coined the term responsive web design over a decade ago, has recently said that media-query-less layouts are certainly within bounds:

Can we consider a flexible layout to be “responsive” if it doesn’t use any media queries, but only uses container queries? [...] I’d be inclined to answer: yes, absolutely.

Over at CSS-Tricks, Chris had similar thoughts. He issued a challenge to examine how and where media queries are used today, and if they will still be necessary going forward:

A common refrain, from me included, has been that if we had container queries we’d use them for the vast majority of what we use media queries for today. The challenge is: look through your CSS codebase now with fresh eyes knowing how the @container queries currently work. Does that refrain hold up?

Fair enough.
I took the bait and had a look at some of my projects - and yes, most of what I use @media for today can probably be accomplished by @container at some point. Nevertheless, I came up with a few scenarios where I think media queries will still be necessary.


For page layout

Permalink to “For page layout”

While container queries can theoretically be used to control any element, they really shine when applied to reusable, independent components. The canonical example is a card component: a self-contained piece of UI you can put anywhere.

Page layouts, on the other hand, are better suited for media queries in my opinion. Page layouts are usually at the very top level of the DOM, not nested in another container. I’ve never encountered a case where the main page layout had to adapt to any other context than the viewport.

.layout {
    display: grid;
}
@media (min-width: 60em) {
    .layout {
        grid-template-rows: 4rem 1fr auto;
        grid-template-columns: 25% 1fr;
        grid-template-areas: 
            "header header"
            "sidebar main"
            "footer footer";
    }
}

For global tokens

Permalink to “For global tokens”

Another good usecase for media queries is to set global design tokens, like spacing or font-sizes. With CSS custom properties it’s now much easier to have fine-grain control over global styles for different devices.

For example, you might want to have bigger text and more whitespace on a large TV than you want for a mobile screen. A larger screen means the user’s head will be physically farther away.

It only makes sense to use a media query there - since the reason for the change is the size of the device itself, not the width of any specific element.

:root {
    /* Font Sizes */
    --font-size-headline-l: 1.875rem; 
    --font-size-headline-m: 1.75rem; 
    --font-size-headline-s: 1.5rem;
    --font-size-copy-l: 1.125rem;
    --font-size-copy-s: 0.875rem;

    /* Global Spacing */
    --spacing-x: 1rem;
    --spacing-y: 1rem;
}
@media (min-width: 48em) {
    :root {
        --font-size-headline-l: 2.5rem;
        --font-size-headline-m: 2rem;
        --font-size-headline-s: 1.75rem;
        --font-size-copy-l: 1.25rem;
        --font-size-copy-s: 1rem;

        --spacing-x: 2rem;
        --spacing-y: 2rem;
    }
}

Permalink to “For user preference and actual “media” queries”

Screen dimensions are not the only things we can detect with media queries. The Media Queries Level 4 Spec (with Level 5 currently a working draft) lists many different queries related to user preference, like:

  • prefers-reduced-motion
  • prefers-contrast
  • prefers-reduced-transparency
  • prefers-color-scheme
  • inverted-colors
  • and others

We can use these to better tailor an experience to the current user’s specific needs.

Other media queries allow for micro-optimizations based on a device’s input method (i.e. touch or mouse):

/* fine pointers (mouse) can hit smaller checkboxes */
@media (pointer: fine) {
  input[type="checkbox"] {
    width: 1rem;
    height: 1rem;
    border-width: 1px;
    border-color: blue;
  }
}

/* coarse pointers (touch) need larger hit areas */
@media (pointer: coarse) {
  input[type="checkbox"] {
    width: 2rem;
    height: 2rem;
    border-width: 2px;
  }
}

Finally, there are actual “media type” queries like @media print that won’t go anywhere. And there are experimental ideas being discussed for new media queries, like this one for “foldable” devices:

Samsung Galaxy Fold Z
:root {
    --sidebar-width: 5rem;
}
/* if there's a single, vertical fold in the device's screen, 
   expand the sidebar width to cover the entire left side. */
@media (spanning: single-fold-vertical) {
    :root {
        --sidebar-width: env(fold-left);
    }
}
main {
    display: grid;
    grid-template-columns: var(--sidebar-width) 1fr;
}

For fixed-to-window stuff

Permalink to “For fixed-to-window stuff”

Components that are taken out of the normal document flow don’t have to care about their containers. Some UI elements are fixed to the viewport itself, usually oriented along an edge of the screen.

Have a look at Twitter’s “Messages” tab at the bottom of the screen for example. Its relevant container is the window, so it makes sense to use a media query here and only apply position: fixed at some breakpoint.

For heights

Permalink to “For heights”

The current implementation of @container only allows querying the width of an element (its “inline” axis), not its height.

👉 Update: Miriam tells me that it is possible to query the height of containers, provided they are defined as size rather than inline-size. The exact value name of this is still in flux at the time of writing.

Style adjustments in relation to width are probably the primary use case for most UI elements anyway, but there are still cases where screen height is an issue. Here’s an example from a “hero image” component:

.hero {
    display:flex;
    flex-direction: column;
    height: 100vh;
}
/* if the screen is really tall, don't fill all of it */
@media (min-height: 60em) {
    .hero {
        height: 75vh;
    }
}

Permalink to “Mix Container Queries and Media Queries”

While I think container queries will eventually replace most “low level” responsive logic, there are still a lot of good usecases for trusty media queries.

A combination of both techniques will probably be the best way forward. @media can handle the big picture stuff, user preferences and global styles; @container will take care of all the micro-adjustments in the components themselves.

A perfect team!

  1. We also still need media queries for the `sizes` attribute of responsive images.

  2. This is fantastic! Although "There’s rarely ever more than one main layout on a page" Have you _seen_ my clients?!

  3. aren’t media queries riot componen’s container query?

Show All Webmentions (68)
  1. 😅 haha ah right, the marketing pages I was thinking about classic top-level header/content/footer stuff... But "content" can ofc contain 600 teaser sections with some carousels sprinkled in

  2. Any day Max publishes an article (about CSS) is a good day. He has answers to the question “With container queries now on the horizon - will we need media queries at all?” mxb.dev/blog/media-que…

  3. I love this! And 100% agreed on all terms. Page layout and global design tokens are my main reasons to say media queries aren't going away soon. Also, I use Grid and Flexbox for some component layouts, so I also don't think I'll use CQs for every component layout need.

  4. Thanks Sara! Yeah "intrinsic" layouts like smart grids are my favorite solution to all of this. Simple and elegant. 💯

  5. So, will we need media queries at all in the future? Probably yes: – @container will replace most low level responsive logic. – @media for big picture stuf, user prefs and global styles. – @container for micro-adjustments of the components. mxb.dev/blog/media-que… by @mxbck

  6. This was a great read. Very well detailed and covers evrything. 100% agree with this!

  7. Good Post. Thank you Max!

  8. This is a great article on what will become @/container, & where we still need @/media.

  9. Really liked this post by @mxbck, which I read as a handy reminder that it’s not media queries OR container queries—they’ll be most effective when used in concert, for the tasks they’re each designed for. mxb.dev/blog/media-que…

  10. Media queries != responsive design. Responsive design is having elements adapt to context. That's all. Media queries were just one tool to achieve that. All we had was a hammer. But the hammer is not the craft. mxb.dev/blog/media-que…

  11. Hi 👋 @mxbck Is compatibility for the all browsers ?

  12. if you're asking about support for container queries - no browser supports them yet. they are an experimental feature currently only implemented in "Chrome Canary", the unstable version of Chrome.

  13. Leo

  14. Para después de la mudanza

  15. #CSS Media Queries in Times of @\container by @mxbck, aka "can we do responsive web design only using container queries". TLDNR you could but there's still a lot of @\media that can help with layout, toekns, user preferences for example for the big picture mxb.dev/blog/media-que…

  16. i've never understood why web devs ask questions like this. "will we still need X / can we stop using X now that we have Y?" when X and Y do two different things and it was never intended to be a replacement grid doesn't replace flex at-container doesn't replace at-media

  17. this is not a dig at @mxbck but at anyone with the mindset that any new css feature is necessarily a total replacement of some other

  18. I agree! Perhaps the tweet is abit misleading. The post is more about figuring out which usecases are better suited for CQ and which for @/media.

  19. yup, it's very helpful. it just reminds me of web devs with that certain mindset and posts like this seem necessary to clear things up (in addition to helping people who are just overwhelmed by the different options and tools)

  20. I didn't know this. Was reading this discussion on whether media queries have a future and it was looking at the pointers feature that tests for the pointing device and its accuracy. #CSS mxb.dev/blog/media-que…

  21. Max Böck: With container queries now on the horizon – will we need media queries at all? Is there a future where we build responsive interfaces completely without them? As Max details we will still need both, but will see a shift from some Media Queries to Container Queries. Good read; I found myself nodding along for the entirety of the post. Media Queries in Times of Container Queries →

  22. @nhoizey right, just had a conversation with @nilsbinder about this! Intrinsic layout is usually the best option since you don't have to give up flow like you do with containment.

  23. @mxbck exactly! 👍Less control is often good.Intrinsic layout as much as possible, and Container Queries when necessary make a good mix IMHO.And some Media Queries for specific cases you list in your post. 👍@nilsbinder

  24. Some of this is outdated though (post is from 2021) and I learned a ton of new things listening to @mia today, so you know, your experience may vary 😅