I want to know the difference between vh and % unit. I wasn’t able to find a satisfactory answer online. Also, I want to know the when to use which unit %, vh, em, rem and other css units.
I won’t be much help for the second portion of your question as I feel like it’s based on scenario/personal preference. Regarding the first portion however:
vh is the viewport height. the number you attach is a percentage so
height: 100vh will be the 100% height of whatever the device is.
% is the portion of the container the element is held inside of so
height: 100% will be the height of the container.
It’s easier to visualize. Gimme a min and I’ll see if I can show it.
The red and blue boxes are
<div> containers (equal size) to hold the green and yellow
<h1> elments. The green
<h1> is set to 30% and is 30% of the
<div> container it is within. The yellow
<h1> is set to 30vh and is 30% of your screen size (try zooming in and out to see it change size while the 30% does not).
The way I see it is like this:
vh and vw are the percentage of the actual viewport (browser window, smartphone, tablet…)
10vh is similar to 10% of the viewport height.
100vw is similar to 100% of the viewport width.
%s work in the same way but for ANY container they are inside, which also includes the viewport.
I have a wrapper div that is
width: 100%. That is exactly the same as
I have a content div inside, which is
width: 50%, which is exactly the same as
50vw because the wrapper is 100% of the viewport.
Now, If I set another div called content inner, and set
width: 100vw, that will try to fill the whole viewport. What I’d need to do is set it to
width: 100%, so that the content inner div is 100% of the content div width not the entire viewport.
Thank you @JesseHope for an easy explanation.
If we use vh for the html as a parent then % would be same as vh.
Is it preferred to use vh in designing web page compared to the %?
@abhigk You’re welcome!
I try not to set hard rules such as “always use vh over %” however personally, I feel that vh lends to a more responsive web page.
Just remember that %s are all about how much of a parent container to use, while vh/vw are always about how much of the screen/viewport to use. Look at these sliders I made that shows you how vw ignores the width of its parent container.