+
80
-

css如何实现保持容器的长宽比?

css如何实现保持容器的长宽比?


网友回复

+
0
-

两种方式

1、width与padding-bottom实现,兼容性强

2、aspect-ratio现在浏览器兼容,老浏览器不兼容

两则的示例代码:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum=1.0,minimum=1.0,user-scalable=0" />

     <style>
.container {
  position: relative;
  width: 100%;  
  padding-bottom: 50%; /* 宽高比为2:1 */
}

.inner {
    background: green;
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0; 
  right: 0;
}
.container2 {
    width: 100%;  
   aspect-ratio: 16 / 9;  /* 设置宽高比 */
}


.inner2 {  
    background: yellow;

  height: 100%;
  width: 100%;
}
      </style>
</head>
<body>
    <div class="container">
        <div class="inner">
            111
        </div>
    </div>

     <div class="container2">
        <div class="inner2">
            222
        </div>
    </div>
</body>
</html>

我知道答案,我要回答