Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
24  
What is a drawing, if not a random bunch of magic numbers (think of strokes between 2 (x,y) points, or arrays of pixels, etc.) that happen to look nice? – Tibo yesterday
51  
Does CSS have variables? Does SVG? – Oded yesterday
27  
This is why many larger projects have a CSS preprocessor like SASS or LESS that supports variables. – Ixrec yesterday
8  
Why? Because they aren't magic numbers. CSS holds data, unlike a program which holds instructions. Although CSS is arguably turing complete, it is not a programming language. – Derek 朕會功夫 yesterday
2  
@BenjaminGruenbaum - still not a standard and not cross-browser. And certainly wasn't in CSS until very recently. – Oded 18 hours ago

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.

share|improve this answer
9  
Some values are indeed just chosen because "they look good". But the example the OP linked contains the same value several times, but it's not clear if they represent the same thing or only have the same value by coincidence. Also it uses a value of 198px which is the difference of the size of something else (200px) and a 2px border. – CodesInChaos yesterday
1  
@CodesInChaos: Yes, there are some cases where variables or some kind of dependency expressions would be cool. – JacquesB yesterday
14  
Note that CSS does support variables – phihag yesterday
14  
@phihag In the specs, yes, but in the wild, not so much (I don't consider 40% global support at the time of this comment as "widely supported". However, you're right in saying that, in the future, we will have CSS variables. And I did learn something new today, so thanks for that. – phyrfox yesterday
2  
@phihag Good luck building compatible sites with CSS variables. – Derek 朕會功夫 yesterday

It's acceptable because these formats are not code, but data. If you were to remove all the "magic numbers," you would essentially duplicate every label, and end up with ridiculous looking files like:

mainkite_width = 200px
...
.mainkite {
  width: mainkite_width;
  ...

Every time you needed to change some data, you would need to look in two places. Granted, there are situations where it's nice to avoid duplication, like if you have a color that is repeated frequently and you may want to change in order to change themes. There are preprocessors and proposed extensions to address those situations, but in general, it's desirable to have numbers together with the structure in a data format.

share|improve this answer
10  
+1 because :"It's acceptable because these formats are not code, but data." – Pieter B 15 hours ago
    
"Granted, there are situations where it's nice to avoid duplication, like if you have a color that is repeated frequently and you may want to change in order to change themes." - Probably better done with classes anyway: .main_color { color: .. }, and using that class is the method of deduplication – Izkata 11 hours ago

The prohibition on magic numbers is the primordial version of this design principle:

Make decisions in one place.

These are not magic numbers. At least not as far as any coding style guide I know of is concerned.

width: 200px;
height: 200px;

They are clearly labeled. Sure, the numbers happen to be the same. But the width is the width and the height is the height. They are designed to vary independently.

Now if you have 5 objects that all had to have the same width and each independently hardcoded their width I would beat you with the indirection stick.

I wouldn't call them magic numbers if they are labeled, but I'd still beat you with the indirection stick.

share|improve this answer
4  
If you had enough objects to need a variable, you have enough objects to create a new class. – Jaketr00 yesterday
    
This is the best answer, as it shows the point: Those are not magic numbers. – TheBlastOne 22 hours ago
2  
" 5 objects that all had to have the same width and each independently hardcoded their width I would beat you with a stick." Welcome to the fun world of web design. – whatsisname 22 hours ago
1  
Magic numbers are not only problematic because of "Make decisions in one place" (aka DRY), but also because they are hard to understand. – sleske 17 hours ago
    
Is there an alternative to being beat with a stick? – djechlin 7 hours ago

Because CSS is not a programming language, instead, it is the config file that contains the variable data for your program.

Currently CSS is so powerful that you can actually program in it, but that is beside the point. In essence it's still a stylesheet langauge.

Lets take a step back. Imagine we have a programming language that can draw on a screen. Imagine we want to program it to paint a web page.

At first we would enter tons of magic numbers in our code. The margin width, the text height, indentations etc. etc.

jump(100) // the margin
drawTable(500, 500)
writeText("Hello World", 12)

So we extract the magic numbers, and put them on top of our file.

int margin = 100
int table = 500
int text_size = 12
jump(margin) // the margin
drawTable(table, table)
writeText("Hello World", text_size)

Now this is a bit ugly, we rather read our variable numbers from a configuration file.

margin 100
table 500
text size 12

Mm, that's a bit unclear... What do those numbers mean? What do those names mean? Lets formalize it a bit.

margin_left 10em
table_width 500px
table_height 500px
font_size 12px

But you know, we want to expand our program a little bit. We also want it to draw pages with multiple tables, pages without tables, pages with paragraphs or buttons and what more. Lets add selectors to our config file so we can specify what paragraph should have a larger font, or different text colour, perhaps we can support nested elements, perhaps we can use a general property in our config file, and then override it with a specific one in a few nested elements.


You feel where this is going, eventually you arrive as CSS. (And a browser to render it.)

Should we then add capabilities to our config file so we can avoid magic numbers again? Add variables? Add a config file for our CSS file? Feels a bit pointless if you remember our CSS file is that very same config file already.

But that is not true of course, your CSS file grows larger and larger, eventually you run into the same problems as with the original magic numbers, the same number repeated all over the place, sometimes with a small transformations etc. Modern CSS however, allows many ways to avoid this repetition. You can use classes that apply to many elements, you can set style for all divs, but then override one specifically, and CSS 3 even allows some kind of variable usage.

That does not mean you need to start using CSS variable in every possible location, use it where it makes sense, use it where you avoid duplication or where other techniques also available fall short.

In the end, you do not want too many magic numbers in your config file either :-)

share|improve this answer

Magic numbers should be avoided for several reasons: One, if their use hides connections between numbers that might change. As an example from another post, if width = 200, height = 200, border = 2, width plus border = 202, height plus two borders = 204, then you want constants for 200 and 2, so that you can change just these two and everything else changes automatically.

Another reason is to hide constants. Let's say you assumed that an hour is 60 minutes. And you are quite sure that isn't going to change in the near future. However, someone else will have used the number 60 for some totally different purpose (like the height of a button). If you want to get rid of the magic 60 for button height, which is a good idea, you run into 100s of "60" that are the number of minutes in an hour. So you can use a constant meaning clearly "numberOfMinutesInAnHour" and use that when appropriate, and now other magic numbers can be found a lot easier.

It's worse when a GUI has been drawn and the numbers taking from the drawing, so lots of buttons that should all be 200 pixels wide have different widths from 198 to 202. Using constants instead of magic numbers then fixes your buttons (because there are people who notice that your UI looks crooked) and avoids bad surprises when you change things.

share|improve this answer
4  
This does not seem to answer the question. The question is "why are magic numbers accepted in CSS/SVG", and you answer "why are magic numbers problematic". – sleske 17 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.