** 前言: ** CSS 中的 display:inline-block 是筆者最為喜歡的元素之一,可以將原本占據一行的塊級元素,轉變為可以并列顯示的行內塊級元素。
空白間距
display:inline-block 常被用來代替float進行頁面布局,不過正所謂金無足赤、人無完人,當使用 inline-block 后會出現“4px”的空白間距。
關于如何消除這 “ 4px ” 的空白間距,網上已經有了不少方法,其中個人覺得用font-size:0 解決空白間距是最為方便簡單的了。
下面做個簡單的Demo
.html
<body>
<div class="a"></div>
<div class="b"></div>
</body>
.css
.a{
width: 100px;
height: 100px;
background: #1c8cff;
display: inline-block;
}
.b{
width: 100px;
height: 100px;
background: #676767;
display: inline-block;
}
Paste_Image.png
接著為兩個盒子的父元素添加 font-size:0
body{
font-size: 0;
}
Paste_Image.png
元素下沉
另外,當給inline-block元素中添加東西時,發現其元素也會隨之下沉。
.html
<body>
<div class="a"><span>test</span></div>
<div class="b"></div>
<div class="c"></div>
</body>
.css
body{
font-size: 0;
}
.a{
width: 100px;
height: 100px;
background: #1c8cff;
display: inline-block;
font-size: 21px;
}
.b{
width: 100px;
height: 100px;
background: #676767;
display: inline-block;
}
.c{
width: 100px;
height: 100px;
background: #00a74a;
display: inline-block;
}
Paste_Image.png
而解決方法可以用vertical-align屬性。
.css
.a{
width: 100px;
height: 100px;
background: #1c8cff;
display: inline-block;
vertical-align: top;
font-size: 21px;
}
Paste_Image.png