纯css设置元素高度与宽度相等


设置图片高度等于宽度

.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;
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM