DEV Community

Timo Hausmann
Timo Hausmann

Posted on

1

Easy media query breakpoint variables in Next.js

Problem

In web projects of any size, you want to keep your magic numbers to a minimum – for example your CSS Breakpoints.

A magic number is a unique value with unexplained meaning or multiple occurrences which could (preferably) be replaced with a named constant.

- Wikipedia

Instead of writing @media (min-width: 768px) 100 times, we want to use a variable for 768px. By design, CSS variables cannot be used in media queries though.

Solution

Enter @include_media (Website) (GitHub).

A Sass Mixin that allows you to write media queries like this:

.header {
  @include media(">phone", "<=tablet") {
    background: red;
  }
}
Enter fullscreen mode Exit fullscreen mode

But how to make it play nicely with Next.js?

First, install it, and if you haven't yet, install sass, too.

npm i -D include-media sass
Enter fullscreen mode Exit fullscreen mode

To use the mixin in your entire codebase, we can import it in next.config.js:

const nextConfig = {
  sassOptions: {
    additionalData: `@import "./node_modules/include-media/dist/_include-media.scss";`
  },
};
Enter fullscreen mode Exit fullscreen mode

For my React components, I use CSS modules. Since Next.js has built-in Sass support, we only have to rename the files to *.sass, for example Header.module.scss. Inside this file, you can now easily use the mixin:

.header {
  padding: 1rem;
  @include media(">phone", "<=tablet") {
    background: red;
  }
}
Enter fullscreen mode Exit fullscreen mode

JSX:

import styles from 'Header.module.scss';

export function Header() {
  return (
    <div className={styles.header}>
      <h1>Resize browser window to see it in action</h1>
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

Customization options and the default breakpoints can be found on the Website and in the Docs.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay