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.
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;
}
}
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
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";`
},
};
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;
}
}
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>
)
}
Customization options and the default breakpoints can be found on the Website and in the Docs.
Top comments (0)