Managing Flow and Rhythm with CSS Custom Properties

Web Design

Design & Dev / Web Design - 77 Views 0

Andy Bell rings out a call for a more flexible method of achieving consistent vertical rhythm across components within a page. Using a technique of CSS custom properties to establish spacing inherited through the cascade, you can make sure your choir are all singing from the same song sheet.


Brought to you by The CSS Layout Workshop. Does developing layouts with CSS seem like hard work? How much time could you save without all the trial and error? Are you ready to really learn CSS layout?


An important part of designing user interfaces is creating consistent vertical rhythm between elements. Creating consistent, predictable space doesn’t just make your web pages and views look better, but it can also improve the scan-ability.

Browsers ship with default CSS and these styles often create consistent rhythm for flow elements out of the box. The problem is though that we often reset these styles with a reset. Elements such as <div> and <section> also have no default margin or padding associated with them.

I’ve tried all sorts of weird and wonderful techniques to find a balance between using inherited CSS while also levelling the playing field for component driven front-ends with very little success. This experimentation is how I landed on the flow utility, though and I’m going to show you how it works. Let’s dive in!

The Flow utility

With the ever-growing number of folks working with component libraries and design systems, we could benefit from a utility that creates space for us, only when it’s appropriate to do so. The problem with my previous attempts at fixing this is that the spacing values were very rigid.

That’s fine for 90% of contexts, but sometimes, it’s handy to be able to tweak the values based on the exact context of your component. This is where CSS Custom Properties come in handy.

The code

.flow {
  --flow-space: 1em;
}  

.flow > * + * { 
  margin-top: var(--flow-space);
}

What this code does is enable you to add a class of flow to an element which will then add margin-top to sibling elements within that element. We use the lobotomised owl selector to select these siblings. This approach enables an almost anonymous and automatic system which is ideal for component library based front-ends where components probably don’t have any idea what surrounds them.

The other important part of this utility is the usage of the --flow-space custom property. We

Read from 24 ways

Comments