DEV Community

Percentages in CSS: you're using them wrong

Massimo Artizzu on December 08, 2019

... 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 { b...
Collapse
 
oenonono profile image
Junk

One quarter of my feedback in CSS code reviews is: make this a variable, name it meaningfully, and show the math.

Collapse
 
aritdeveloper profile image
Arit Developer

Interesting read! Personally I would probably use Flexbox to achieve the same. I'm just now getting into SASS and I am loving it! The more intuitive code is, the better (for me, anyways 😄)

Collapse
 
cutemaxi profile image
Oparaononaku maximus

Am hearing SASS for the first time, how does it operate?

Collapse
 
maxart2501 profile image
Massimo Artizzu

Basically, just like SCSS. Before SCSS there was SASS.

SASS is a preprocessor that introduced a new syntax that was fundamentally different from CSS. For example, there is no need of curly braces (it is "pythonic" in this sense) or semicolons at the end. But plain CSS can't be parsed as SASS, so they later introduced a new syntax that's compatible with CSS. And SCSS was born.

So SASS is SCSS with the older syntax. I don't know, though, if the new advancements in SCSS will be available in SASS too (i.e. @use and all the rest).

Collapse
 
jcpuxd profile image
John Park

I'm having a hard time understanding the type of background image this would be beneficial for... Do you have an example? I've used percentage for lifestyle shots where I want to position subjects into the element bounds in a specific way. The percentages are unique to that image, would this still apply?

Collapse
 
maxart2501 profile image
Massimo Artizzu

Yes, of course that would. Any time you don't know the size of a box, but you want something placed in the "same position", is a good fix for percentage positioning.

In my case, that was simpler. In the left half of the page we had the content; in the right, the disegner decided to have some padding from the boundaries, so there you go.

Collapse
 
skamansam profile image
Samuel

You don't need sass or less to take advantage of variables. CSS has native support.

Collapse
 
maxart2501 profile image
Massimo Artizzu

That's correct, as I've explained in the article 🙂

However, I usually rely very little on custom properties, as they're evaluated at runtime. This has advantages, of course, but with a (computational) price. If I know a value won't change during the lifetime of a page, and I can precisely fix the scope of it, I normally use preprocessor variables and all the nice tools and builtin functions preprocessors usually give.

That's why I won't stop using preprocessors any time soon.

Collapse
 
felipperegazio profile image
Felippe Regazio

in a perfect world, --header-height would exist on every css project out there ;P