PostCSS is a tool that developers can use to write CSS in a familiar way. Additionally it gives them the flexibility of a pre-processor.
By the end of this article, you’ll know how to:
1. Install or run PostCSS
2. Build your PostCSS into an output file
2. Replace SASS variables
3. Replace SASS nested rules
4. Use named media queries
Installing & Running
PostCSS is best used in conjunction with a build tool such as Parcel or Webpack but can also used via their command line tool (CLI).
Instead of installing the command line tool, we can use npx to run any commands needed. The npx command pulls a package, runs the command with the arguments given, and then deletes itself. This is great for one time use tools or if you want to keep your filesystem clean.
This command executes the following steps…
1. Tells PostCSS to look for a file named css/app.css
2. Compiles the css
3. Outputs the new css into a file named main.css
In SASS/SCSS, you declare variables the $ symbol. With PostCSS, you have several options.
1. Install the postcss-nested-vars plugin, which enables SASS style variables
2. Refactor your variables into native CSS variables
I recommend using option 2. Using native CSS variables removes some overhead, as you don’t need a plugin. Not to mention, they’re fun to use! They also offer you flexibility since CSS variables can be changed in real time. Think of the possibilities!
Writing CSS variables is easy. To declare global variables, you can add them to a :root element. This will wrap them into a global context of sorts. You can also declare variables inside of another selector if you wanted.
PostCSS, by default, does not include support for nested selectors. Yet, this functionality can be enabled through the use of the postcss-nested plugin. But before we do that, we need to create a configuration file.
This configuration file tells PostCSS what plugins to use and where they’re located. You can name the file anything, but for best practices, it’s best to name it postcss.config.js. Place this file in the root of your project.
Next, initialize an npm project.
Now install the plugin.
Now when you run your PostCSS command you can specify that you have a settings file using the -c flag.
With that out of the way, you can now write nested selectors that will expand.
Named Media Queries
If you’re like me, you’ve grown accustomed to naming your CSS queries. The postcss-custom-media plugin lets you do exactly that.
Here I’ve defined a new media query named small-viewport using the @custom-media directive. When you use this query, you reference it using the @media directive.
I hope you have learned a little bit about PostCSS and how you can begin using it today. There are many plugins that extend the abilities of PostCSS that make it an invaluable tool to have.