参考于一个很好的试验场: https://wow.techbrood.com/fiddle/15713
Key points
1.padding值(百分数) 是基于宽度设定的,例如宽度是300px (padding-top: 50% 就是150px)
2.子元素伪类设置padding-top撑开元素,并设置定位定位到【0,0】原点
3.利用子元素padding-top控制宽高比
由于使用padding-top控制子元素高度
长/宽 = 2/1 padding-top的值为 100 / (2/1) => 50%
长/宽 = 788 / 433 padding-top的值为 100 / (788 / 433 )=> 54.9492385786802%
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
body {
background: orange;
color: #222;
}
.box {
display: inline-block;
position: relative;
width: 20%;
margin: 5% 5% 0 0;
float: left;
font-size: 12px;
}
.box:before {
content: "";
display: block;
padding-top: 100%;
}
.ratio2_1:before {
padding-top: 50%;
}
.ratio1_2:before {
padding-top: 200%;
}
.ratio4_3:before {
padding-top: 75%;
}
.ratio16_9:before {
padding-top: 56.25%;
}
.content {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
background: black;
padding: 30px;
text-align: center;
vertical-align: center;
text-transform: uppercase;
color: #fff;
}
.content span {
font-weight: bold;
font-size: 3em;
display: block;
}
</style>
</head>
<body>
<div class="box ratio1_1">
<div class="content">Aspect ratio of <span>1:1</span>
</div>
</div>
<div class="box ratio2_1">
<div class="content">Aspect ratio of <span>2:1</span>
</div>
</div>
<div class="box ratio1_2">
<div class="content">Aspect ratio of <span>1:2</span>
</div>
</div>
<div class="box ratio4_3">
<div class="content">Aspect ratio of <span>4:3</span>
</div>
</div>
<div class="box ratio16_9">
<div class="content">Aspect ratio of <span>16:9</span>
</div>
</div>
</body>
</html>