实际效果
需求
- 已知父元素(box)为一个正方形
- 但不知道父元素实际尺寸(自适应)
- 现在需要往正方形里面放4张图片,且图片相互之间有留白
实现方式
- 先看
dom
结构:
<body>
<div class="box">
<div class="sub sub1"></div>
<div class="sub sub2"></div>
<div class="sub sub3"></div>
<div class="sub sub4"></div>
</div>
</body>
- 父元素基本样式:
* {
margin: 0;
padding: 0;
}
html,
body {
height: 100%;
}
body {
display: flex;
justify-content: center;
align-items: center;
}
.box {
width: 30%;
background: #e5e5e5;
}
- 子元素实现样式:
.sub {
width: 48%;
height: 0;
padding-bottom: 48%;
background-image: url("./img/image1.jpg");
background-repeat: no-repeat;
background-position: center;
background-size: cover;
float: left;
margin-right: 2%;
margin-bottom: 2%;
}
.sub:nth-of-type(2) {
background-image: url("./img/image2.jpg");
margin-left: 2%;
margin-right: 0;
}
.sub:nth-of-type(4) {
background-image: url("./img/image4.jpg");
margin: 2% 0 0 2%;
}
.sub:nth-of-type(3) {
clear: both;
background-image: url("./img/image3.jpg");
margin-bottom: 0;
margin-top: 2%;
}
例子相关图片
总结
-
padding
结合height: 0;
是实现此功能的关键 - 本来开始是使用
css
的object-fit
属性配合<img>
标签实现图片的自适应展示 - 后因为
object-fit
不能兼容ie,且必须指定高度,遂使用背景图方式实现 - 工作中经常会遇到由于是自适应屏幕导致我们不能写固定宽高,这个时候就需要通过类似方式来获取合适的宽高
- 仅当个人笔记使用,如果有更好的方法回应留言区讨论,一起学习
完整代码
- 最后附完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
html,
body {
height: 100%;
}
body {
display: flex;
justify-content: center;
align-items: center;
}
.box {
width: 30%;
background: #e5e5e5;
}
.sub {
width: 48%;
height: 0;
padding-bottom: 48%;
background-image: url("./img/image1.jpg");
background-repeat: no-repeat;
background-position: center;
background-size: cover;
float: left;
margin-right: 2%;
margin-bottom: 2%;
}
.sub:nth-of-type(2) {
background-image: url("./img/image2.jpg");
margin-left: 2%;
margin-right: 0;
}
.sub:nth-of-type(4) {
background-image: url("./img/image4.jpg");
margin: 2% 0 0 2%;
}
.sub:nth-of-type(3) {
clear: both;
background-image: url("./img/image3.jpg");
margin-bottom: 0;
margin-top: 2%;
}
</style>
</head>
<body>
<div class="box">
<div class="sub sub1"></div>
<div class="sub sub2"></div>
<div class="sub sub3"></div>
<div class="sub sub4"></div>
</div>
</body>
</html>