設置圖片高度等於寬度
.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;
}