在業(yè)務(wù)開(kāi)發(fā)中,遇到這樣一個(gè)問(wèn)題:
有不同大小的圖片门躯,橫排成一行排列淆党,寬度已經(jīng)設(shè)為相同,圖片適應(yīng)成不同高度⊙攘梗現(xiàn)在需要讓包裹圖片的標(biāo)簽等高染乌,通過(guò)css有什么方法實(shí)現(xiàn)呢?
解決
先建立一個(gè)模型懂讯。
// index.html
<style>
.item {
background: blue;
float: left;
width: 100px;
}
</style>
<div class="wrapper">
<div class="item" style="height: 300px"></div>
<div class="item" style="height: 200px"></div>
<div class="item" style="height: 100px"></div>
</div>
方法1:使用padding/margin
.wrapper {
overflow: hidden
}
.item {
float: left;
padding-bottom: 3000px;
padding-margin: -3000px;
}
或者
.wrapper {
overflow: hidden;
// font-size: 0;
}
.item {
display: inline-block;
padding-bottom: 3000px;
margin-bottom: -3000px;
vertical-align: top;
font-size: 12px;
}
通過(guò)padding-bottom
撐開(kāi)元素的高度;再使用margin-bottom
和overflow:hidden
隱藏內(nèi)容外的高度荷憋。將值設(shè)成一個(gè)較大的值,一般能覆蓋所有可能的高度褐望。
如果不使用float: left
還可以使用display:inline-block
勒庄。由于inline-block
相當(dāng)于父元素的行內(nèi)元素,元素之間會(huì)有空隙譬挚,需要在父元素上設(shè)置font-size:0
锅铅,并在后面的子孫元素中恢復(fù)值;同時(shí)行內(nèi)元素默認(rèn)從底部對(duì)齊减宣,上方會(huì)出現(xiàn)空隙盐须,需要設(shè)置vertiacal-align:top
,將元素從頂部對(duì)齊漆腌。
這種方式兼容性好贼邓,但是看上去比較hack阶冈, 語(yǔ)義性不好,一眼讓人看不懂想做什么塑径。
方法2:使用table
使用
<table>
<tr>
<td>
<div class="item" style="height: 300px"></div>
</td>
<td>
<div class="item" style="height: 200px"></div>
</td>
<td>
<div class="item" style="height: 100px"></div>
</td>
</tr>
</table>
利用table來(lái)實(shí)現(xiàn)女坑,同一行下的td是等高的。
這種方式兼容性也很好统舀,但是要使用額外的table元素去包裹匆骗,有標(biāo)簽冗余。
方法3:使用display
// html
<style>
.wrapper {
display: table-row;
}
.item {
display: table-cell;
}
</style>
和上面使用table的原理一樣誉简,同時(shí)可以應(yīng)用在已有的元素上碉就。觀察table可以發(fā)現(xiàn),table闷串、tr瓮钥、td也是使用了display屬性來(lái)實(shí)現(xiàn)的。
這種方式兼容性好烹吵,同時(shí)也不用添加額外的標(biāo)簽碉熄,語(yǔ)義性也更好。