CSS Units - What is the difference between vh/vw and %?

Richard Hamilton picture Richard Hamilton · Jun 25, 2015 · Viewed 75k times · Source

I just learned about a new and uncommon CSS unit. vh and vw measure the percentage of height and width of the viewport respectively.

I looked at this question from Stack Overflow, but it made the units look even more similar.

How does vw and vh unit works

The answer specifically says

vw and vh are a percentage of the window width and height, respectively: 100vw is 100% of the width, 80vw is 80%, etc.

This seems like the exact same as the % unit, which is more common.

In Developer Tools, I tried changing the values from vw/vh to % and viceversa and got the same result.

Is there a difference between the two? If not, why were these new units introduced to CSS3?

Answer

Josh Beam picture Josh Beam · Jun 25, 2015

100% can be 100% of the height of anything. For example, if I have a parent div that's 1000px tall, and a child div that is at 100% height, then that child div could theoretically be much taller than the height of the viewport, or much smaller than the height of the viewport, even though that div is set at 100% height.

If I instead make that child div set at 100vh, then it'll only fill up 100% of the height of the viewport, and not necessarily the parent div.

body,
html {
    height: 100%;
}

.parent {
    background: lightblue;
    float: left;
    height: 200px;
    padding: 10px;
    width: 50px;
}

.child {
    background: pink;
    height: 100%;
    width: 100%;
}

.viewport-height {
    background: gray;
    float: right;
    height: 100vh;
    width: 50px;
}
<div class="parent">
    <div class="child">
        100% height
        (parent is 200px)
    </div>
</div>

<div class="viewport-height">
    100vh height
</div>