1.百分比
适用场景:
height=100% (为视口高度)
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
html,body{
width: 100%;
height: 100%;
padding: 0;
margin: 0;
}
.container {
height: 100%;
}
.top{
height: 20%;
background-color: deeppink;
}
.center{
height: 50%;
background-color: greenyellow;
}
.center .left{
width: 30%;
height: 100%;
float:left;
background-color: deepskyblue;
}
.center .right{
width: 70%;
height: 100%;
float: right;
}
.bottom{
height: 30%;
background-color: purple;
}
</style>
</head>
<body>
<div class="container">
<div class="top">top 20%</div>
<div class="center">
<div class="left">left 30%</div>
<div class="right">right 70%</div>
</div>
<div class="bottom">bottom 30%</div>
</div>
</body>
</html>
效果图
2.rem(css3语法)
适用场景:针对视口的不同宽度范围,设定元素不同的宽高
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
@media screen and (max-width: 400px){
html{
font-size:12px;
}
}
@media screen and (min-width: 401px) and (max-width: 600px) {
html {
font-size:20px;
}
}
@media screen and (min-width: 601px) and (min-width: 601px) {
html {
font-size:30px;
}
}
.rem{
height: 20rem;
width:20rem;
background-color: grey;
}
</style>
</head>
<body>
<div class="container">
<div class="rem">rem</div>
</div>
</body>
</html>
可以保证盒子的宽高比例,但是只能设置几个特定的视口值,不能做到视口每改变一像素,盒子就改变宽高。
3.@mixin aspect-ratio(width,height) sass语法
适用场景:在即使body的高度不定的情况下,可以保证盒子的宽高比例不变。 设定盒子宽的百分比, 高根据设定的宽高比,可以自动适配,很好用~~
<style>
@mixin aspect-ratio($width, $height) {
position: relative;
&:before {
display: block;
content: "";
width: 100%;
padding-top: ($height / $width) * 100%;
}
> .content {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
}
.top{
//引入上面的样式,设置top这个盒子宽高比例为9:6
@include aspect-ratio(9,6);
width:80%;
background-color:pink;
}
</style>
<body>
<div class="top">
<div class="content">
//top盒子的子盒子要写在content里面,语法规定
<span class="num">1<span>
</div>
</div>
</body>
4.vw、vh
适用场景:当字体大小需要根据视口宽度而改变大小时,
vw做单位是个不错的选择
1vw = 视口宽/100
#box{
font-size: 2vw;
}
如果此时视口宽为800px,那么box的字体大小 = 2*(800/100) = 16px
1万+

被折叠的 条评论
为什么被折叠?



