inline-block會(huì)引起元素和元素之間幾個(gè)像素的間隙(具體間隙大小取決于字體大邢掠)。造成空白間隙的原因是在標(biāo)簽和標(biāo)簽之間使用了空格或換行符蕾久。因?yàn)榭瞻鬃址扑疲彩亲址矔?huì)引用CSS樣式
對(duì)于<div>標(biāo)簽:
代碼如下:
<div class="left">
<div class="one"></div>
<div class="tow"></div>
</div>
.left{
width: 100px;
height: 100px;
margin: 100px 100px;
background-color: #4cae4c;
}
.one{
width: 30px;
height: 30px;
background-color:red;
display: inline-block;
}
.tow{
width: 30px;
height: 30px;
background-color:black;
}
效果如下:
解決方法1:設(shè)置父元素的font-size為0,在子元素重新設(shè)置字體大小僧著。
.left{
width: 100px;
height: 100px;
margin: 100px 100px;
background-color: #4cae4c;
font-size: 0;
}
.one{
width: 30px;
height: 30px;
background-color:red;
display: inline-block;
}
.tow{
width: 30px;
height: 30px;
background-color:black;
}
解決辦法2: 利用負(fù)margin-bottom/top/left/right(不推薦履因,具體負(fù)margin多少取決于字體的大小)
.left{
width: 100px;
height: 100px;
margin: 100px 100px;
background-color: #4cae4c;
}
.one{
width: 30px;
height: 30px;
background-color:red;
display: inline-block;
margin-bottom: -4px;
}
.tow{
width: 30px;
height: 30px;
background-color:black;
}
或者
.one{
width: 30px;
height: 30px;
background-color:red;
display: inline-block;
}
.tow{
width: 30px;
height: 30px;
background-color:black;
margin-top: -4px;
}
解決方法3:在設(shè)置display:inline-block的div里面寫入任意的文字
.left{
width: 100px;
height: 100px;
margin: 100px 100px;
background-color: #4cae4c;
}
.one{
width: 30px;
height: 30px;
background-color:red;
display: inline-block;
}
.tow{
width: 30px;
height: 30px;
background-color:blueviolet;
}
<div class="left">
<div class="one">1</div>
<div class="tow"></div>
</div>
但是如果只給沒有設(shè)置display:inline-block的div加文字盹愚,會(huì)沒有效果搓逾。
對(duì)于<span>或者<ul><li>標(biāo)簽:
<div class="left">
<span class="one">我是1</span>
<span class="tow">我是2</span>
</div>
.left{
width: 100px;
height: 100px;
margin: 100px 100px;
background-color: #4cae4c;
}
.one{
width: 30px;
height: 30px;
background-color:red;
}
.tow{
width: 30px;
height: 30px;
background-color:blueviolet;
}
解決方法1:移除標(biāo)簽間的空格
寫法1:
<div class="left">
<span class="one">我是1</span><span class="tow">我是2</span>
</div>
寫法2:
<div class="left">
<span class="one">我是1
</span><span class="tow">我是2</span>
</div>
寫法3:利用HTML注釋標(biāo)簽
<div class="left">
<span class="one">我是1</span><!--
--><span class="tow">我是2</span>
</div>
仔細(xì)看的話第一種和第二種方法之間還有差別!
解決方法2:取消標(biāo)簽閉合
把span標(biāo)簽的結(jié)束標(biāo)簽去掉杯拐,這樣間隙就沒有了。但是為了兼容IE6/IE7世蔗,最后一個(gè)標(biāo)簽需要閉合端逼。
<div class="left">
<span class="one">我是1
<span class="tow">我是2</span>
</div>
解決方法3:letter-spacing(字符邊距)為負(fù)值 or word-spacing(單詞邊距) 負(fù)值
給父級(jí)元素加上
.left{
width: 100px;
height: 100px;
margin: 100px 100px;
background-color: #4cae4c;
word-spacing: -5px;
}
.one{
width: 30px;
height: 30px;
background-color:red;
}
.tow{
width: 30px;
height: 30px;
background-color:blueviolet;
}