1、为什么要给图片留出加载空间?
为图像指定 height 和 width 属性是一个好习惯。如果设置了这些属性,就可以在页面加载时为图像预留空间。
如果没有这些属性,浏览器就无法了解图像的尺寸,也就无法为图像保留合适的空间,因此当图像加载时,页面的布局就会发生变化,这样会影响加载速度的页面效果,最好的办法就是给图片留出空间,使加载图片过程中不影响图片下方内容的渲染。
2、通过padding设置宽高比一定的容器
padding取值为百分比时,是基于父元素宽度设置百分比的,所以当我们设置一个宽高比为5:2的容器时,可以这么写
.banner{
width: 100%;
padding-top: 40%;
}
3、用padding实现图片自适应布局根据图片
宽高比,用padding属性设置容器大小,img通过绝对定位absolute布局
具体实现如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<style>
*{
margin:0 auto;
}
.container{
width: 100%;
position: relative;
overflow: hidden;
}
.container > div{
width: 40%;
float: left;
position: relative;
border: 1px solid #ccc;
margin-bottom: 20px;
}
.container > div:after {
content: '\20';
padding-top:56.5%;
display: block;
}
img{
width: 100%;
height: 100%;
position: absolute;
left: 0;
top: 0;
}
</style>
<body>
<div class="container">
<div>
<img src="https://www.baidu.com/img/bd_logo1.png">
</div>
<div>
<img src="https://www.baidu.com/img/bd_logo1.png">
</div>
<div>
<img src="https://www.baidu.com/img/bd_logo1.png">
</div>
</div>
</body>
</html>