CSS – Why Are Magic Numbers Acceptable in CSS and SVGs?

clean codecode-qualitycoding-stylecsssvg

Often times I see questions on the Hot Network Questions list like this that basically ask "how do I draw this arbitrary shape in CSS". Invariably the answer is a couple of blocks of CSS or SVG data with a bunch of seemingly random hard-coded values that form the requested shape.

When I look at this, I think 'Yuck! What an ugly block of code. I hope I never see this type of stuff in my project'. However, I see these types of Q&As quite frequently and with a high number of upvotes, so clearly the community doesn't think they are bad.

But why is this acceptable? Coming from my back-end experience this makes no sense to me. So why is it OK for CSS/SVG?

Best Answer

Firstly, magic values are avoided in programming by using variables or constants. CSS does not support variables, so even if magic values were frowned on, you don't have much of a choice (except using a preprocessor as SASS, but you wouldn't do that for a single snippet).

Secondly, values might not be as magic in a domain specific language like CSS. In programming, a magic number is a number where the meaning or intent is not obvious. If a line says:

x += 23;

You will ask "why 23"? What is the reasoning? A variable could clarify the intent:

x += defaultHttpTimeoutSeconds;

This is because a lone number could mean absolutely anything in general purpose code. But consider CSS:

background-color: #ffffff;
font-size: 16px;

The height and color are not magic, because the meaning is perfectly clear from the context. And the reason for choosing the spefic value is simple because the designers thought it would look good. Introducing a variable would not help anything, since you would just name it something like "defaultBackgroundColor" and "defaultFontSize" anyway.

Related Topic