Skip to navigation Skip to content

Now on NPM: Convert your pixels to rems or ems using this PostCSS plugin

Two-minute read

Have you every had a dozen people coming over for dinner in 20 minutes only to discover that you need to convert a bunch of CSS with items sized in pixels over to relative sizes such as rems or ems? Who doesn’t face this problem at least several times a week.

Up until now the only way to fix this problem was to learn assembly language, make your own CPUs and write your own operating system. Well, no more!

postcss-pixels-to-rem is a PostCSS plugin that finds several types of pixel notations and converts them to either rems or ems. It is designed as a way to bring legacy SASS files written using pixels to rem mixins forward and into the postCSS world with as seamlessly as possible.

For example, it’s intended as a fix for legacy code that uses the now deprecated Bourbon px to rem and px to em mixins.

Does it work? Well, you’re soaking in it! The CSS for this site is compiled with it.

How it works

It takes in several types of notations and spits out finished CSS at the other end.

  • Notation of rem(<value>) or em(<value>) is converted to <value>rem and <value>em respectively.
  • Notation of <value>px is converted to <value>rem.

It also allows for several user-set options.

  • Base font size. Default is 16px.
  • Default unit. Setting it to rem or em will override rem(<value>) or em(<value>) notation. All items will be output in the user-set unit.
  • Media queries can be excluded from conversion.
  • Specific declarations can be excluded from conversion, e.g. border-width.

How to use it

After reading this, everyone will want to get their hands on postcss-pixels-to-rem. No need to resort to The Purge style theft and murder 1. There’s plenty to go around at the low, low price of free 2.

Unfortunately we released it a little too late for Valentine’s, Mother’s Day and graduation gift-giving, but there’s still birthdays and anniversaries – and don’t forget all-important early Christmas shopping.

It’s available over here on NPM. Or install it by:

npm install --save-dev postcss-pixels-to-rem

To use it with Gulp:

var postcss = require('gulp-postcss')
var pixelstorem = require('postcss-pixels-to-rem');    

and

gulp.task('css', function() {
    var plugins = [
        pixelstorem()
    ];      
gulp.src('source/sass/styles.scss')
.pipe(postcss(plugins))
.pipe(gulp.dest(public/css));
});

Find full installation and usage instructions here on NPM or Github.

postcss-pixels-to-rem not only comes with a full money-back guarantee, and is also guaranteed to make you better looking, thinner, wittier, more popular and bring you happiness, all while converting your pixels to rems or ems.

  1. Unless you want to.
  2. We deal in volume and pass the savings on to our customers.