El primer método: atributo css: relación de aspecto: la relación de aspecto de la caja;
1) Su valor de atributo puede ser 1; 1.2; 0.2; 1/2; 3/2; 2.2/3.2
2) Por supuesto, también puedes incluir un calc (no es necesario superfluo);
3) Tenga en cuenta que el porcentaje no se puede establecer, incluso si está envuelto con calc, es inútil
Este atributo también es relativamente simple de usar.
<!DOCTYPE html>
<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>
.test-box{
width: 100%;
aspect-ratio: 8/1;
background: red;
}
</style>
</head>
<body>
<div class="test-box"></div>
</body>
</html>
Este atributo también se puede usar para respuestas
/* 最小宽高比 */
@media (min-aspect-ratio: 8/5) {
div {
background: #9af; /* blue */
}
}
/* 最大宽高比 */
@media (max-aspect-ratio: 3/2) {
div {
background: #9ff; /* cyan */
}
}
/* 明确的宽高比, 放在最下部防止同时满足条件时的覆盖*/
@media (aspect-ratio: 1/1) {
div {
background: #f9a; /* red */
}
}
优点:
用着简单方便,不会增加多余dom
缺点:
兼容性比较差,除非你们不考虑老一点的版本;比如google浏览器版本要100+版本才支持,80就不支持
El segundo método: usar relleno para abrir la caja; principio: el porcentaje de configuración de relleno se calcula en función del ancho de la caja
<!DOCTYPE html>
<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>
.test-box-container{
position: relative;
padding-top: 40%;
width: 100%;
}
.test-box{
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: red;
}
</style>
</head>
<body>
<div class="test-box-container">
<div class="test-box">
</div>
</div>
</body>
</html>
优点:
没有啥兼容问题,可以放心使用
缺点:
每用一次就会添加一个冗余的dom盒子