Screenshot of Momu website with blue rectangles highlighting the spacings

Spacings and CSS Custom properties

This article was first published on Base Design website.

Early on when working on the website for Antwerp’s fashion museum MoMu, we decided to follow a more systematic approach to design. It made a lot of sense for the project, as it had to be a scalable system much more than a custom designed set of pages.

On top of that, it seemed obvious that it would improve the overall workflow from design to development. Code is by definition systematic, while design is not. So by making design more systematic, it should prove easier to code.

As part of the design system, we tried to use a defined set of—as few as possible—vertical spacings between modules and elements. In the end we came up with 4 types of spacing: 25 pixels, 75 pixels, 175 pixels and 250 pixels.

Of course, in the design we adapted those 4 spaces responsively. Here’s a table that shows how each defined space updates to another value as it encounters a CSS break point.

While studying this table, we realized pretty soon we could use a rather new technique to convert the spacings in the design to code. We defined CSS Custom Properties at the root of the document like so:

With this list of CSS Custom Properties that vary for every screen size, we could use them wherever we want in our CSS:

That looks neat! But…

We need an IE Fallback

As you can see in the screenshot above (taken from Can I Use), the support for the CSS Custom Properties is quite good. All the major browsers are supporting this feature except for Internet Explorer. In order to make sure that all visitors browse the website with coherent spacing, we had to make sure we had a fallback in place.

And here is the solution we found: every time we use a spacing, we first set the same CSS Property using a `rem` unit instead of a custom property. The values for the fallback are the same ones as on the tablet version since Internet Explorer users are not on a mobile and rarely on a modern wide screen.

To make everything easy and convenient, we created a mixin that would always first set the fallback of the spacing and then the Custom Properties version. This mixin has two parameters: the type of spacing and the CSS property we want to define. The default values are ‘xl’ for the type and ‘margin-top’ for the CSS property.

We could then call the mixin to apply the appropriate spacing to any element.
Here is an example:

And here is the output from the code above:

Clean and concise!
Especially if you realize that before this technique, we would have had to declare all the spacings for every single break point. You can see how longer it would have been in the example below.

So thanks to Custom Properties the CSS for MoMu’s new website is leaner. Of course less code is always better, because it doesn’t only result in a more maintainable project, it also helps ship a more performant website. Yay!