CSS单位 - vh / vw和%之间有什么区别? [英] CSS Units - What is the difference between vh/vw and %?
问题描述
我刚刚学习了一个新的和不常见的CSS单元。 vh
和 vw
分别测量视口的高度和宽度的百分比。
我从Stack Overflow看过这个问题,但它使单元看起来更加类似。
具体地说
vw和vh分别是窗口宽度和高度的百分比,
:100vw是宽度的100% ,80vw为80%等。
这看起来与%
单位,这是更常见的。
在开发人员工具中,我尝试将值从vw / vh更改为%和反之亦然, p>
两者之间有区别吗?如果没有,为什么这些新单元引入 CSS3
?
100%
可以是任何高度的 100%
。例如,如果我有一个父 div
的 1000px
tall和一个子 div
是 100%
height,那么那个子 div
理论上可能比即使 div
设置为 100%$ c>,视口的高度或远小于视口的高度$ c> height 。
如果我改为将 div
设置为 100vh
,那么它将只填满视口高度的 100%
父母 div
。
请参阅 jsfiddle :
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;
}
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.
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
?
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
.
See this jsfiddle:
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;
}
这篇关于CSS单位 - vh / vw和%之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!