How to use new Media Query syntax in CSS
The implementation of the new Media Queries Level 4
syntax has already appeared in all browsers since Firefox 63+, Chrome 104+.
Why do we need another syntax?
Let's start by comparing both syntaxes:
Old:
.teaser__image {
width: 100%;
}
@media (max-width: 619px) {
.teaser__image {
width: 100px;
}
}
@media (min-width: 620px) and (max-width: 768px) {
.teaser__image {
width: 180px;
}
}
New:
.teaser__image {
width: 100%;
}
@media (width < 620px) {
.teaser__image {
width: 100px;
}
}
@media (620px <= width <= 768px) {
.teaser__image {
width: 180px;
}
}
As we can see, the old syntax is quite cumbersome, and not as intuitive. The new syntax is simple and compact, and close to mathematical comparison operations.
The new syntax can be described in a diagram:
What to do with older browsers?
That's where PostCSS
comes in.
PostCSS is a tool written in Node.js by Andrey Sitnik to automate CSS routines. PostCSS is also called Post-processor
because it is usually run after the initial compilation of styles. You can extend PostCSS
features with a variety of plugins.
The most famous plugin is autoprefixer
, which is used by many, but not many people know that it is designed as a plugin for PostCSS
.
A lot of PostCSS
plugins allow us to write code using the latest CSS
features, compiling everything into code that older browsers understand.
Switch to the new syntax
Install the PostCSS
plugin:
npm i -D postcss postcss-media-minmax
Create a file postcss.config.js
to configure PostCSS
.
const mediaMinMax = require('postcss-media-minmax');
module.exports = {
plugins: [mediaMinMax],
};
Let's plug in PostCSS
. This already depends on the builder tool you are using.
Eleventy
As an example for the static site generator Eleventy
(on which this blog runs) integration code would be:
npm i -D eleventy-postcss-extension
Add to .eleventy.js
:
const pluginCSS = require('eleventy-postcss-extension')
eleventyConfig.addPlugin(pluginCSS)
Gulp
For Gulp
you will need to install additionally:
npm i -D gulp-postcss
And then add to the pipeline:
const postcss = require('gulp-postcss');
// gulp code here
.pipe(postcss())
The plugins will be included from the configuration file we have created earlier.
Nuxt
Nuxt supports PostCSS
out of the box. Therefore, to enable plugins you just need to add them to the corresponding section of the nuxt.config.js
configuration file:
export default defineNuxtConfig({
...
postcss: {
plugins: {
'postcss-media-minmax': {},
},
},
...
})
References: