Determining CSS Units For Your Pattern Library

For some time now I’ve been working on an inherited codebase, moving it from it’s original single purpose of being a website to a cohesive design language with a pattern library and front-end framework.

One part of doing this is looking at the existing code to see if it’s possible to improve it and, as one of our underlying goals, make it easier to understand and more ‘human-readable’.

In doing that we’ve uncovered a few things that could be improved and more consistent. One of those things is how CSS units are being used.

Types Of Units

There are quite a few lengths of CSS available and looking at the existing CSS (that currently uses Sass) we have found these 5 being used:

The majority of the time a rem is in use with a px fallback for Old IE. This is using a Sass mixin to create the rem value from the px value variable used in the mixin.

All of the units are found in use for fonts, margins, paddings, borders, widths, heights, line-heights and media queries. Along with things like box-shadow and text-shadow.

As we are trying to make the CSS used within the pattern library easier to read and understand I’m now looking at ‘guidelines’ as to what CSS unit should be used where.

Categorising CSS Unit Usage

So far I’ve got this:

ems

The em unit is only to be used within media queries. Currently most media queries are created using a Sass mixin and variable or value to define the min-width.

px

I think we must restrict the use of px to box-shadow, text-shadow, border and height. Anything that could look a little bit silly when you zoom on a desktop browsers.

rem

Any font-size or vertical spacing should use the rem unit. To have consistent rhythm if the browser is resized or in between media queries.

%

Percentages should be used only for all things horizontal. Widths, left and right margins or padding.

unitless

We should not use any CSS unit when defining our line-height.

vh

A ‘special’. The vh unit is currently only used on one aspect of the homepage.

Moving forward

In defining new guidelines and implementing them on a codebase it can create better consistency within the pattern library and overall design language. This will help the maintainability, the usage and the development of the codebase.

Although deciding upon, defining and sticking to guidelines for such a marginal part of the codebase could seem a little over-engineered there are several improvements of this ‘size’ in the works which should lead to a better, more consistent design system which I hope will empower other teams to start using it on their projects.