1. 程式人生 > >display:inline-block列表佈局經常會遇到的“換行符/空格間隙問題”

display:inline-block列表佈局經常會遇到的“換行符/空格間隙問題”

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>居中導航</title>
    <style>
        ul{text-align: center;height: 30px;line-height: 30px;/*background-color: #f00*/;}
        li, a{display: inline-block;width: 80px;height: 100%;background-color: #f00;}
        li
{/*margin: 0 -4px;*/list-style: none;} a, li.cur a{color: green;text-decoration: none;} a:hover, li.cur a{background-color: #c00}
</style> </head> <body> <ul class="m-nav"> <li><a href="#">推薦</a></li> <li class="cur"><a
href="#">
歌單</a></li> <li><a href="#">大牌DJ</a></li> <li><a href="#">歌手</a></li> <li><a href="#">新碟上架</a></li> </ul> </body> </html>

這裡寫圖片描述

diasplay:inline-block產生間隙原因:inline-block元素間有空格或是換行了間隙。

方法一:li{font-size:0;}

適用範圍:只適用於圖片間的間隙。不適用於表單中有文字的表單項。font-size會清除文字。
這裡寫圖片描述

方法二:設定letter-spacing

<style>
        ul{ /*font-size: 0;*/ text-align: center;height: 30px;line-height: 30px;/*background-color: #f00*/;letter-spacing: -8px;}
        /*在ul中設定letter-spacing使每個li間距為-8px,間隙就變沒  了*/
        li, a{display: inline-block;width: 80px;height: 100%;background-color: #f00;}
        li{/*margin: 0 -4px;*/list-style: none;letter-spacing: 0px;}/*在li裡設定letter-spacing恢復為0,正常顯示*/
        a, li.cur a{color: green;text-decoration: none;}
        a:hover, li.cur a{background-color: #c00}
    </style>

方法三:設定li的margin。li{margin: 0 -4px;}

li{margin: 0 -4px;list-style: none;}

這裡寫圖片描述