How to get Magic Numbers in CSS?
Despite the super fun sounding name, magic numbers are a bad thing. It is an old school programming term for “unnamed numerical constant”. As in, just some number plunked into the code that is probably vital to things working correctly but are very difficult for anyone not intimately familiar with the code to understand what it is for. CSS is loaded with unnamed numerical constants, but they are usually paired with properties and in the context of a selector so there is little mystery. There are magic numbers in CSS though, and they are still bad.
Magic numbers in CSS refer to values which “work” under some circumstances but are frail and prone to break when those circumstances change. They are usually always related to fonts in some way or another. They are created by an author who likely only tested in their own browser under ideal conditions. Let’s take a look at some examples so we all know what they are and hopefully can avoid them in the future.
Look at this simple set of tabs:
Each of the tabs is set to
width: 100px;. In this example 100px is our “magic number.” There are any number of things that can go wrong with this. Simply adding another tab with longer text demonstrates that:
A bit awkward and likely undesirable. We could prevent the wrapping with
white-space: nowrap; but that’s possibly worse:
Our tabs would be less prone to breakage if we use min-width instead:
Or perhaps no width at all:
If you were dead-set on having all the tabs the same size, you could do
overflow: hidden; and
text-overflow: ellipsis; perhaps:
In that case, you’d probably want a
title attribute so there is some way to reveal the entire tab name. You might think this could be solved from the Content Management System side by only allowing tab names to be a certain number of characters long. But what about users who increase font-size from their end for accessibility reasons? This fixed sizing might be hurting them.