Text emphasized alt text example
A cartoon skull with a hotpink hat on.1 min read

Custom Media Feature Flags

css
2,389 views · 15 active

A fun use case for @custom-media queries is to toggle styles based on a feature flag.

Imagine an edge worker that toggles true or false in a CSS file, and the rest of your styles can tap in and adapt.

  • A/B testing
  • Unique user features
  • Reveal Debug elements
  • v2 layouts

you name it.

Syntax #

Define an enabled feature like:

@custom-media --feature-flag true;

Or a disabled feature like:

@custom-media --debug-flag false;

Use them like:

@media (--feature-flag) {
  body {

  }
}

.component {
  @media (--debug-flag) {

  }
}

Use nesting, query from JavaScript, or both.

More custom media #

The spec, a CSS Tricks article, post by Stefan Judis, a polyfill, a premade set in Open Props (anticipating the feature), and there's been good browser implementation activity recently in Firefox (marked FIXED!) and Chrome, not webkit as much.

I'm excited, it's a great feature.

64likes
16reposts

Join the conversation on

Curious as to the benefits of this versus @container style() queries. e.g. @custom-media --feature-flag-custom-media true; @media (--feature-flag-custom-media) { ... } versus :root { --feature-flag-style-query: true; } @container style(--feature-flag-style-query: true) { ... }
Andrew HudsonAndrew Hudson