Introducing the vr unit to create simple vertical rhythm—using PostCSS
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.
Function-able Sass
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 64px
.
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 font
property:
The font-size can be either em
, rem
, px
or %
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 32px
.
Once this is set up, we can now use the vr
unit:
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: .5vr
, .25vr
.
Thoughts
If you have any feedback, please leave a comment below or you can find me on Twitter. If you’d like to know more more about PostCSS, I wrote about it here. Happy vertical rhythm-ing!