DEV Community

Alex
Alex

Posted on

4

Breakpoints variables with pure CSS

In CSS can use variables most of the time.

:root {
  --color-main: red;
}
Enter fullscreen mode Exit fullscreen mode

But, can't use variables in @media queries.

@media (min-width: var(--br-md) {
/* will never work */
}
Enter fullscreen mode Exit fullscreen mode

Unexpected solution is to use @container queries:

:root {
  --is-tablet: true;

  @media (min-width: 1200px) {
    --is-tablet: false;
  }
}

...

@container style(--is-tablet: false) {
  .content {
    grid-template-areas:
      'header aside'
      'feed   aside';
    grid-template-rows: minmax(7.16rem, 17.6rem) minmax(7.16rem, max-content);
    grid-template-columns: var(--feed-columns);
  }
}

Enter fullscreen mode Exit fullscreen mode

Only downside is Firefox lacks support of it, but it doesn't do so well on many things.

Next.js usage

In Next.js can use postcss-custom-media plugin to achieve same outcome, for all browsers and with css modules.

How it looks like

@custom-media --is-desktop (min-width: 1200px);

...
@media (--is-desktop) {
  .content {
    grid-template-areas:
      'header aside'
      'feed   aside';
    grid-template-rows: minmax(7.16rem, 17.6rem) minmax(7.16rem, max-content);
    grid-template-columns: var(--feed-columns);
    gap: 1.75rem;
    width: 100%;
  }
}

Enter fullscreen mode Exit fullscreen mode

Setup

Official docs

  1. Install all dependencies:
    npm install --save-dev postcss autoprefixer postcss-flexbugs-fixes @csstools/postcss-global-data postcss-custom-media postcss-preset-env

  2. Add PostCSS config to package.json:

  "postcss": {
    "plugins": [
      "postcss-flexbugs-fixes",
      [
        "@csstools/postcss-global-data",
        {
          "files": [
            // need to use file with global variables here
            "core/styles/vars.css"
          ]
        }
      ],
      "postcss-custom-media",
      [
        "postcss-preset-env",
        {
          "autoprefixer": {
            "flexbox": "no-2009"
          },
          "stage": 3,
          "features": {
            "custom-properties": false
          }
        }
      ]
    ]
  }
Enter fullscreen mode Exit fullscreen mode

Postgres on Neon - Get the Free Plan

No credit card required. The database you love, on a serverless platform designed to help you build faster.

Get Postgres on Neon

Top comments (1)

Collapse
 
maxart2501 profile image
Massimo Artizzu

Note: Firefox should add support to container style queries by the end of 2025, as it's in their yearly interop efforts.

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →