设置图片高度等于宽度

.img-box{
  width:100%;
  height:0;
  position: relative;
  padding-bottom: 100%
}
.img-box img{
  width:100%;
  height:100%;
  position: absolute;
}

如果仅仅想要外层div同宽高,而图片保持原图大小不被撑大, 可以将图片属性换成下面这个

.img-box img{
  max-width:100%;
  max-height:100%;
  margin: auto;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

如果子元素根据父元素设置宽度,那么将其高度设置为0,并将padding-bottom设置为百分比,则该子元素的高度将根据它的宽度计算

.img-box{
      width:400px;
      height:800px;
}
.img-box img{
      width:100%;
      height:0;
      padding-bottom:100%;
      background-color: #0f8bcb;
}  

如果子元素是图片,需要使用下面的方法

.img-box-parent{
      width:400px;
      height:800px;
}
.img-box{
      width:100%;
      height:0;
      padding-bottom:100%;
      position: relative;
}
.img-box img{
      width:100%;
      height:100%;
      position: absolute;
      top:0;
      left:0;
}
posted on 2021-10-25 10:47  夜攸  阅读(1467)  评论(0编辑  收藏  举报