(转)css实现盒子高度随宽度等比例缩放的四种方式
    		       		warning:
    		            这篇文章距离上次修改已过443天,其中的内容可能已经有所变动。
    		        
        		                
                CSS可以通过多种方式实现盒子高度随宽度等比缩放。以下是四种常见的方法:
- 使用
padding属性: 
.box {
  width: 100%; /* 设定宽度 */
  padding-top: 56.25%; /* 设定高度,宽高比为100%/56.25% */
  position: relative;
  background-color: #f1f1f1;
}
.box-content {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}- 使用
aspect-ratio属性(CSS Aspect Ratio Level 1): 
.box {
  width: 100%;
  aspect-ratio: 16 / 9; /* 设定宽高比为16:9 */
  background-color: #f1f1f1;
}- 使用
vw视口单位: 
.box {
  width: 100%;
  height: 56.25vw; /* 宽高比为100%/56.25%的视口宽度百分比 */
  background-color: #f1f1f1;
}- 使用
:after伪元素: 
.box {
  width: 100%;
  position: relative;
  background-color: #f1f1f1;
}
.box:after {
  content: '';
  display: block;
  padding-top: 56.25%; /* 设定高度,宽高比为100%/56.25% */
}
.box-content {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}以上四种方法均可以实现盒子高度随宽度等比缩放的效果。选择哪种方法取决于具体需求和浏览器兼容性要求。
评论已关闭