我刚刚了解了一个新的和不常见的CSS单元。Vh和vw分别测量视口高度和宽度的百分比。
我从Stack Overflow中看到了这个问题,但它让单位看起来更加相似。
vw和vh单位是如何工作的
答案明确地说
Vw和vh是窗宽和窗高的百分比,
分别为:100vw为宽度的100%,80vw为宽度的80%,等等。
这似乎与%单位完全相同,后者更常见。
在开发人员工具中,我尝试将值从vw/vh更改为%,反之亦然,得到了相同的结果。
这两者之间有什么区别吗?如果不是,为什么这些新单位被引入到CSS3?
我知道这个问题很老了,@Josh Beam提到了最大的区别,但还有一个问题:
Suppose you have a <div>, direct child of <body> that you want filling the whole viewport, so you use width: 100vw; height: 100vh;. It all works just the same as width: 100%; height: 100vh; until you add more content and a vertical scrollbar shows up. Since the vw account for the scrollbar as part of the viewport, width: 100vw; will be slightly bigger than width: 100%;. This little difference ends up adding a horizontal scrollbar (required for the user to see that little extra width) and by consequence, the height would also be a little different on both cases.
在决定使用哪一个时,即使父元素大小与文档视口大小相同,也必须考虑到这一点。
例子:
使用宽度:100大众;
.fullviewport {
宽度:100大众;
身高:100 vh;
背景颜色:红色;
}
.extracontent {
宽度:100大众;
高度:20 vh;
背景颜色:蓝色;
}
< html >
身体< >
< div class = " fullviewport " > < / div >
< div class = " extracontent " > < / div >
身体< / >
< / html >
使用宽度:100%;:
.fullviewport {
宽度:100%;
身高:100 vh;
背景颜色:红色;
}
.extracontent {
宽度:100%;
高度:20 vh;
背景颜色:蓝色;
}
< html >
身体< >
< div class = " fullviewport " > < / div >
< div class = " extracontent " > < / div >
身体< / >
< / html >
我知道这个问题很老了,@Josh Beam提到了最大的区别,但还有一个问题:
Suppose you have a <div>, direct child of <body> that you want filling the whole viewport, so you use width: 100vw; height: 100vh;. It all works just the same as width: 100%; height: 100vh; until you add more content and a vertical scrollbar shows up. Since the vw account for the scrollbar as part of the viewport, width: 100vw; will be slightly bigger than width: 100%;. This little difference ends up adding a horizontal scrollbar (required for the user to see that little extra width) and by consequence, the height would also be a little different on both cases.
在决定使用哪一个时,即使父元素大小与文档视口大小相同,也必须考虑到这一点。
例子:
使用宽度:100大众;
.fullviewport {
宽度:100大众;
身高:100 vh;
背景颜色:红色;
}
.extracontent {
宽度:100大众;
高度:20 vh;
背景颜色:蓝色;
}
< html >
身体< >
< div class = " fullviewport " > < / div >
< div class = " extracontent " > < / div >
身体< / >
< / html >
使用宽度:100%;:
.fullviewport {
宽度:100%;
身高:100 vh;
背景颜色:红色;
}
.extracontent {
宽度:100%;
高度:20 vh;
背景颜色:蓝色;
}
< html >
身体< >
< div class = " fullviewport " > < / div >
< div class = " extracontent " > < / div >
身体< / >
< / html >
100%可以是任何物体高度的100%。例如,如果我有一个1000px高的父div,和一个100%高的子div,那么这个子div理论上可能比视口的高度高得多,或者比视口的高度小得多,即使这个div被设置为100%高。
如果我将子div设置为100vh,那么它只会填充视口高度的100%,而不一定是父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>