With Sass, I use a function to create simple vertical rhyhtm—generated from the base line-height—without the complexity of maintaining a baseline grid. With PostCSS, we can take this further and create a new unit.
The Sass (SCSS) function I use is very simple. It essentially returns a multiple of the base line-height to help create vertical rhythm. The function looks a little like this:
And we can use it in our stylesheet like this:
This will multiply the line-height by the number passed in, so the result here would be
Extending with PostCSS
After digging into PostCSS, I decided to re-create the Sass function with a PostCSS plugin. Because PostCSS is a post-processer, we are able to extend CSS. The result was postcss-vertical-rhythm, which replicates the Sass function, but using a custom CSS unit—
vr—instead of a function. For example:
This method works more like using plain CSS.
How do I use the vr unit?
Firstly, install postcss-vertical-rhythm via npm:
If you’re using gulp, you can then add it to your project like this:
Next, we need to define the base font-size and line-height using the shorthand
The font-size can be either
% based. postcss-vertical-rhythm will parse the property and calculate the
px line-height value automatically—no variable set up required. In the case above, the line-height would be
Once this is set up, we can now use the
And with the line-height at
32px from the above font property, the output is:
postcss-vertical-rhythm also supports decimal values so we can easily use half or quarter values, for example: