純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