传统方式
<!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>
.item {
background-color: pink;
width: 50%;
margin: 0 auto;
}
.inner {
width: 100%;
height: 0;
padding-bottom: 75%;
position: relative;
}
.container {
position: absolute;
inset: 0;
}
</style>
</head>
<body>
<div class="item">
<div class="inner">
<div class="container"></div>
</div>
</div>
</body>
</html>
aspect-ratio (会有兼容性问题低版本浏览器不兼容)
<!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>
.body {
width: 50%;
aspect-ratio: 4/3;
background-color: pink;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="body"></div>
</body>
</html>