DEV Community

Cover image for CSS percentage unit, the evil parts

CSS percentage unit, the evil parts

Abdelrahman Ismail on April 28, 2018

CSS has dozens of length units, but the percentage unit is one of my favorites. However, it can be very evil and troublesome sometimes. It should ...
Collapse
 
sadarshannaiynar profile image
Adarsh

Nice article! How did you get to make the code snippet screenshot?

Collapse
 
ismail9k profile image
Abdelrahman Ismail

Thank you 😄😄, I used carbon.now.sh

Collapse
 
salchichongallo profile image
Jimmy Murillo

I thought you used Polacode

Thread Thread
 
ismail9k profile image
Abdelrahman Ismail

Woow!! Great extension.
I believe I'll use it in my next article, thank you 😃

Collapse
 
bilalunal profile image
Bilal Ünal

Hey! Thanks for sharing. I have a question. I use calc method to center elements in a relative div. For example in .slider__next div i used top(50% + 15px/2); rule to center it on vertical. What do you think about it, is this way useful?

Collapse
 
ismail9k profile image
Abdelrahman Ismail

My pleasure 😄😄, I think you meant using .slider__next { top: calc(50% - 15px/2); }.

It will work here because you know the height of the element already; so you can simply subtract half of its hight from the top position.

But in other scenarios, the height of the element will be unknown for example a text paragraph, in most cases, you can't know exactly its height.(suppose it positioned absolute) the transform technique will be better here.

example

text paragraph example

There are cases, where the height of the element will change in mobile (using a media query), so you have to change it again by subtracting the new height.

There are many ways to center elements (flex-box, grid,... ), so use the way that suits your situation best.