方式一:padding + 百分比
<style>
html,
body {
margin: 0;
padding: 0;
}
.outer {
20%;
height: 0;
padding-bottom: 20%;
background-color: red;
}
</style>
<body>
<div class="outer"></div>
</body>
方式二:vw+vh
<style>
html,
body {
margin: 0;
padding: 0;
}
.outer {
20vw;
height: 20vw;
background-color: red;
}
</style>
<body>
<div class="outer">
<p>love</p>
</div>
</body>
缺点:会导致在元素上设置的 max-height 属性失效
方式三:伪元素 + margin(padding)-top 撑开容器
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
html,
body {
margin: 0;
padding: 0;
}
.outer {
20%;
background-color: red;
overflow: hidden;
position: relative;
}
.outer::after {
content: "";
display: block;
margin-top: 100%; /* margin 百分比相对父元素宽度计算 */
}
p {
margin: 0;
/* 解决内容,导致容器溢出 */
position: absolute;
}
</style>
</head>
<body>
<div class="outer">
<p>
Lorem, ipsum dolor sit amet consectetur adipisicing elit. Repudiandae,
cupiditate. Labore alias eius magnam, pariatur beatae sed eos dolor non
numquam laudantium dolorem error aspernatur maxime, reiciendis dolorum
exercitationem! Quas?
</p>
</div>
</body>
</html>