In CSS can use variables most of the time.
:root {
--color-main: red;
}
But, can't use variables in @media queries.
@media (min-width: var(--br-md) {
/* will never work */
}
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);
}
}
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%;
}
}
Setup
Official docs
Install all dependencies:
npm install --save-dev postcss autoprefixer postcss-flexbugs-fixes @csstools/postcss-global-data postcss-custom-media postcss-preset-env
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
}
}
]
]
}