一、css使用padding-bottom百分比进行提前占位,防止抖动。
1. 页面加载抖动问题
在html5开发网页中,经常会遇到这样一个问题,比如一个宽度百分百,高度自适应的图片,在网速慢的情况下加载过程中会出现抖动的问题(未加载图片前容器的高度为0,图片加载完成后下面的内容会被挤下去)。
这种问题如果是图片有固定高度,就不会出现加载抖动。但一般情况下,为了使图片不被拉伸,高度一般设为自适应,那么为了防止加载抖动,我们需要给图片提前占个位,这里使用的是css的padding-bottom百分比进行占位。
示例代码如下:
.img-box{
overflow: hidden;
width: 100%;
height: 0;
padding-bottom: 50%;
}
padding-bottom实际上是提前占位了,这个容器的高度始终是0,高度为0还之所以能够显示内容是因为内容溢出在了padding-bottom上,这里的50%是图片的
高宽比例
,切记是相对于父元素宽度
的50%(即.img-box的上一级),不是相对于自己的width,详情请看下面的例子。
案例:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>padding-bottom</title>
<style>
.content{
width: 400px;
height: 400px;
margin: 100px auto;
background-color: aquamarine;
}
.box1{
width: 100%; /* 400px 相对于content的width */
height: 0;
padding-bottom: 50%; /* 200px 相对于content的width */
background-color: red;
}
.box2{
width: 25%; /* 100px 相对于box1的width */
height: 0;
padding-bottom: 25%; /* 100px 相对于box1的width */
background-color: yellow;
}
</style>
</head>
<body>
<div class="content">
<div class="box1">
<div class="box2"></div>
</div>
</div>
</body>
</html>
如图所示:
这种情况下box2中如果有图片宽高比为一比一时(根据padding的百分比),加载过程中就不会出现抖动的情况,同理box1也是如此。
其他方案:
- 使用vw,vh单位
- 如果是微信小程序可以使用rpx