Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

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

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...