视口单位为vw,vh,vmin和vmax
vw单位表示根元素宽度的百分比。1vw等于视口宽度的1%
vh单位表示根元素高度的百分比,一个vh等于视口高度的1%
vmin表示视口的宽度和高度中的较小值,也就是vw 和 vh 中的较小值。如果高度小于宽度,根据高度计算。
vmax与vmin相反,该值是vw 和 vh 中的较大值。
视口单位的用例
字体大小 移动设备上的最小字体大小要大于14px。要解决该最小字体大小,可以使用 calc(),将具有一个最小值14px,并在些基础上添加2vw的值。
.title {
font-size: calc(14px + 2vw);
}
全屏
height: 100vh;
粘性布局(footer) 网站内容有时候很少,footer 没有粘在底部,可以这样改,给内容(content)一个高度,它等于视口高度- (header + footer)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>view port</title>
<style type="text/css">
header,footer {height: 70px;background: blue;}
main {height: calc(100vh - 70px - 70px);background: lightblue;}
</style>
</head>
<body>
<header>test header</header>
<main>test main</main>
<footer>test footer</footer>
</body>
</html>
纵横比 保持其纵横比,而不管视口大小如何。需要先确定所需的纵横比,例如9/16
section {
/* 9/16 * 100 */
height: 56.25vw;
}
流行的顶部边框 如何将固定值转换为视口对象?下面是如何计算它的等效的vw
vw = (Pixel Value / Viewport width) * 100
如vw = (4 / 1440) * 100 = 0.277
.header {
border-top: 4px solid #8f7ebc;
border-top: 0.277vw solid #8f7ebc;
border-top: calc(2px + 0.138vw) solid #8f7ebc;//最好是这个,使用一个基本像素值,视口单元可以是一个附加
}
移动端滚动问题 移动设备中存在一个常见问题,即使使用100vh,也会滚动,原因是地址栏的高度可见
body {
display: flex;
flex-direction: column;
height: 100vh; /* 不支持自定义属性的浏览器的回退 */
height: calc(var(--vh, 1vh) * 100);
background: #ccc;
}
div {
flex: 1;
display: flex;
justify-content: center;
align-items: center;
&:nth-child(even) {
background: #eee;
}
}
// 首先,我们得到视口高度,我们乘以 1% 得到一个vh单位的值
let vh = window.innerHeight * 0.01;
// 然后,将`--vh`自定义属性中的值设置为文档的根目录一个属性
document.documentElement.style.setProperty('--vh', `${vh}px`);
<div>Item 1</div>
<div>Item 2</div>
<div>Item 3</div>
<div>Item 4</div>
<div>Item 5</div>