If you’re looking to tidy up your CSS media queries, you’ve landed in the right place. PostCSS Sort Media Queries is a powerful PostCSS plugin that helps you keep your CSS organized, whether you’re adopting a mobile-first or desktop-first approach. In this guide, we’ll walk you through the installation, usage, and configurations of this essential tool.
Table of Contents
Online Demo
Take a look at the online demo to see how this plugin works in action!
Examples
Mobile First Sorting
Here’s a quick look at how the plugin organizes mobile-first queries:
/* Before */
@media screen and (max-width: 640px) {
.head { color: #cfcfcf; }
}
@media screen and (max-width: 768px) {
.footer { color: #cfcfcf; }
}
/* After */
@media screen and (max-width: 768px) {
.footer { color: #cfcfcf; }
}
@media screen and (max-width: 640px) {
.head, .main, .footer { color: #cfcfcf; }
}
Desktop First Sorting
Similarly, here’s how it looks for desktop-first queries:
/* Before */
@media screen and (width: 640px) {
.header { color: #cdcdcd; }
}
/* After */
@media screen and (max-width: 760px) {
.footer { color: #cdcdcd; }
}
@media screen and (min-width: 760px) {
.desktop-first { color: #cdcdcd; }
}
Install
To get started, you’ll need to install the module. Run the following command:
npm install postcss postcss-sort-media-queries --save-dev
Usage
Check your project for an existing PostCSS configuration in postcss.config.js, or within the postcss section of package.json.
If you’re already using PostCSS, add the plugin to your plugins list:
module.exports = {
plugins: [
require('postcss-sort-media-queries')({ sort: 'mobile-first' }),
require('autoprefixer'),
]
};
Options
The sorting mechanism relies on the sort-css-media-queries function. You have several options at your disposal:
- sort: Choose from ‘mobile-first’, ‘desktop-first’, or a custom sorting function.
- Only Top Level: Set
onlyTopLevel: trueto sort only the top-level media queries, keeping nested ones in place.
Changelog
For the latest updates, check the Releases history.
License
This plugin is released under the MIT License.
Other PostCSS Plugins
Explore more plugins like postcss-momentum-scrolling, which adds momentum scrolling behavior for overflow elements on iOS.
Troubleshooting
If you encounter issues, consider the following:
- Ensure your PostCSS version is compatible with the plugin.
- Check for typos in your configuration files.
- Look out for conflicting plugins that may affect how media queries are processed.
For more insights, updates, or to collaborate on AI development projects, stay connected with fxis.ai.
At fxis.ai, we believe that such advancements are crucial for the future of AI, as they enable more comprehensive and effective solutions. Our team is continually exploring new methodologies to push the envelope in artificial intelligence, ensuring that our clients benefit from the latest technological innovations.

