Container style media queries

| permalink | css

Browser support: Chrome and Edge only at the time of posting.

Web designers have always wanted to use variables within media queries.

The ideal solution, author-defined environment variables, have not attracted even a hint of vendor interest.

While toggle variables can serve as a workaround, you are forced to combine all the responsive states in a single declaration.

On the other hand, container style queries are already supported by Chromium based browsers and can serve as an almost perfect substitute.

/* set up media queries */
:root {
  @media (width < 640px) {
    --media: sm
  }
  @media (640px <= width < 1024px) {
    --media: md
  }
  @media (1024px <= width) {
    --media: lg
  }
  @media (prefers-reduced-motion) {
    --motion: reduced
  }
}

/* use container style query */
body {
  margin: 3rem;
  @container style(--media:sm) {
    margin: 1rem
  }

  /* advanced usage */
  @container not style(--media:sm) {
    color: red
  }
  @container style(--media:sm) or style(--media:lg) {
    border: 2px solid red
  }
  @container not style(--motion:reduced) {
    /* your transition or animation */
  }
}

Alternately, we can use the variables themselves as Boolean values.

/* boolean only query */
:root {
  @media (width < 640px) {
    --sm:
  }
  @media (640px <= width < 1024px) {
    --md:
  }
  @media (1024px <= width) {
    --lg:
  }
  @media not (prefers-reduced-motion) {
    --motion:
  }
}

body {
  margin: 3rem;
  @container style(--sm) {
    margin: 1rem
  }

  /* advanced usage */
  @container not style(--sm) {
    color: red
  }
  @container style(--sm) or style(--lg) {
    border: 2px solid red
  }
  @container style(--motion) {
    /* your transition or animation */
  }
}

Limitation

Since you can't target the container itself, the root element <html> can't be made responsive.

In closing

With a clear path toward mainline browser support, container style queries provide a relatively clean and ergonomic syntax to abstract away the media query selector.