前端開發中,當我們用<li>來實現橫向導航欄的時候,總是發現中間會出現一條間隙,效果圖如下:
下面是這個效果圖的代碼,可以發現此時每個<li>之間都出現了間隔。
<style>
ul{
background-color: black;
width: 500px;
height: 30px;
border: 1px solid;
}
ul>li{
background-color: white;
list-style: none;
display: inline-block;
width: 100px;
height: 30px;
text-align: center;
line-height: 30px;
}
</style>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
引發這種問題的原因是:<li>標籤之間存在間隙,每個標籤是不連貫的,存在空格。
所以我們的解決方案如下:
一:既然是因爲間隙,最直接的就是去掉間隙。如下。
<ul>
<li>1</li><li>2</li><li>3</li><li>4</li>
</ul>
或者
<ul>
<li>1</li><!--
--><li>2</li><!--
--><li>3</li><!--
--><li>4</li><!--
--></ul>
這種方法雖然解決了標籤之間的間隙,但是感覺代碼的排版雜亂,而且實際開發中比較繁瑣。
二:將<li>的父標籤,也就是<ul>標籤的屬性 font-size:0,再給 li 標籤設置 font-size:...px,代碼如下:
<style>
ul{
background-color: black;
width: 500px;
height: 30px;
border: 1px solid;
font-size: 0;
}
ul>li{
background-color: white;
list-style: none;
display: inline-block;
width: 100px;
height: 30px;
text-align: center;
line-height: 30px;
font-size: 14px;
}
</style>
三:這個方法就方便多了,給 li 標籤設置 float:left; 屬性,我的開發中一般都是用這個方法。
<style>
ul{
background-color: black;
width: 500px;
height: 30px;
border: 1px solid;
}
ul>li{
background-color: white;
list-style: none;
display: inline-block;
width: 100px;
height: 30px;
text-align: center;
line-height: 30px;
float: left;
}
</style>
tips:font-size:0;還可以解決圖片元素img排列時候出現的間隙問題。給img的父級元素設置font-size:0;即可解決間隙問題。