23 October 2022

Spacer elements

Not all whitespace has to be margins; it can just be <div style="height: 24px"> or <Gap heightEm={1}/>. Doing it this way is sometimes necessary and often way more intuitive and easy to maintain.

For example, if you want an element to be vertically spaced but not quite centered, and for the gaps to have a minimum height, that would be a mess with margins. Here’s how you’d do it with spacer elements:

<div id="container">
	<div></div> <!-- top margin -->
	<div id="center">
		Centered
	</div>
	<div></div> <!-- bottom margin -->
</div>
#container {
	display: grid;
	grid-template-rows: minmax(1em, 1fr) auto minmax(1em, 2fr);
}

The grid-template-rows property captures very concisely what we want: a central element sized according to its contents (auto) and spaces either side, with the bottom space twice the size of the top one and each having a minimum size of 1em.

“Always use CSS for whitespace” is one of those dogmas that’s emerged as we’ve figured out how to make websites and realised that tables are generally not the best tool for layout, but spacer elements themselves have been thrown out incorrectly along with those other approaches, in favour of doing everything that can be done in CSS in CSS.