Percentages in CSS: you're using them wrong

Massimo Artizzu - Dec 8 '19 - - Dev Community

... if you do one of the things I'm going to explain.

The motivation for this post came after a colleague wrote something like this:

.foo {
  background-position: 83% 10%;
}
Enter fullscreen mode Exit fullscreen mode

and I was like: "Huh, what?"

Of course, I had no clue of what was going on there. Only after I launched the project I had a hunch of the intent of the code: they were finely positioning an image in the middle of the right half of a container... and 10% from the top, because why not.

This led me to give them an advice I usually give to novices:

If you're using a percentage different from 100% and 50%, there's probably a better approach.

The point is that "100%" is commonly intended as "all the way" and "50%" as "half-way". (Note: I'm not including 0% as you should probably use 0 instead, but the idea is the same.) Any other value - including something apparently "easy" like 25%, 33% or 10% - is more difficult to recognize and understand.

What if I need that value?

Of course, that value could be totally legitimate and the result of a well conceived computation - although in my experience it's usually the result of trial and error 😅 (i.e.: "Does this value look good? Mmm, not quite, I'll add 1% more...").

Fortunately we have plenty of tools to write clearer code and convey the correct meaning. If you're using a preprocessor like SASS or LESS, you can avoid magic numbers altogether with a fine use of meaningfully named variables.

In the case above, the goal was to center horizontally an image on the right half of the container, with a with of 25% of the container. And that 10% was roughly the height of the header. So, ideally, the code would have been something like this:

$header-height: 8rem;
$image-width: 25%;

.foo {
  $bg-position-x: 100% - 50 * $image-width / (100% - $image-width);
  background-position: $bg-position-x $header-height;
}
Enter fullscreen mode Exit fullscreen mode

This still could be improved (the way background images are positioned isn't as simple as one can imagine), but at least it's clear that the position depends on the image's width. And provides the correct value (83.3333...%).

If you're not using a preprocessor, you can still use plain-old CSS, as calc and CSS custom properties are now widely supported:

:root {
  --header-height: 8rem;
  --image-width: 25;
}
.foo {
  --bg-position-x: calc(100% - 50% * var(--image-width) / (100 - var(--image-width)));
  background-position: var(--bg-position-x) var(--header-height);
}
Enter fullscreen mode Exit fullscreen mode

And if you need to support Internet Explorer... why aren't you using a preprocessor? 😱

Conclusion

Please use variables with meaningful names and have mercy on those who will maintain your code 😄

. . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player