先看代碼:
<div class="box">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
.box{font-size: 0;}
.item{
display: inline-block;
position: relative;
width: 25%;
height: 0;
padding-bottom: 25%;
background: red;
}
.item:nth-child(2n){background: #ccc}
這里有兩處解釋一下:
1.給 item 設(shè)置 dispaly:inline-block 讓他能在一行排列且不脫離文檔流缝裁,再設(shè)置寬度為25%蒸辆。此時(shí)原則上四個(gè)排列在一行的 div 贾虽。但由于inline-block自帶屬性讓每個(gè)div之間有間隙 逃糟,解決方法:在父元素box上添加font-size:0的屬性
2.給 item 設(shè)置 height:0;padding-top/bottom:25% ,此時(shí)的padding是根據(jù)窗口的寬度來計(jì)算的。
最后我們?cè)俳oitem下面加上圖片绰咽,item設(shè)置相對(duì)定位菇肃;img設(shè)置絕對(duì)定位、寬高為100%
全部代碼:
<style>
*{padding: 0;margin: 0;}
.box{font-size: 0;}
.item{
display: inline-block;
width: 25%;
height: 0;
padding-bottom: 25%;
background: red;
position: relative;
}
.item:nth-child(2n){background: #ccc}
.item>img{
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
</style>
<body>
<div class="box">
<div class="item">
![](images/headPic.jpg)
</div>
<div class="item">
![](images/headPic.jpg)
</div>
<div class="item">
![](images/headPic.jpg)
</div>
<div class="item">
![](images/headPic.jpg)
</div>
</div>
</body>
</html>