本文介紹了如何創建一個水平菜單,每個項目之間的寬度和間距相等?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
這是我到目前為止所得到的:fiddle
Here's what I've got so far: fiddle
雖然有 2 個問題:
- 我已將每個
li
的寬度硬編碼為33%
,我不想這樣做,以便可以輕松添加更多項目. - 我想在每個項目之間放置一些間距(背景顏色的間隙),但是一旦我添加邊距,一個項目就會被撞到一行.我該如何解決?
- I've hard-coded the width of each
li
to33%
, which I'd prefer not to do so that I can easily add more items. - I want to put some spacing between each item (a gap in the background color), but as soon as I add a margin, one item will be bumped down a line. How do I get around that?
#main-nav {
list-style: none;
margin: 0;
padding: 0;
width: 100%;
overflow: auto;
}
#main-nav li {
float: left;
width: 33%;
height: 25px;
text-align: center;
}
#main-nav li a {
width: 100%;
display: block;
height: 100%;
line-height: 25px;
text-decoration: none;
background-color: #e0e0f0;
font-weight: bold;
color: #021020;
}
#main-nav li a:hover {
background-color: #498cd5;
color: #ddeeee;
}
<ul id="main-nav">
<li><a href="#">one</a></li>
<li><a href="#">two</a></li>
<li><a href="#">three</a></li>
</ul>
推薦答案
參見: http://jsfiddle.net/f6qmm/
display: table
被用來均勻分布動態數量的 li
.不幸的是,在 IE7 中不起作用,所以 *float: left
使用(僅適用于 IE7 及更低版本),因此至少它們都在一條線上 - 盡管它看起來仍然很可怕.
display: table
is being used to evenly space a dynamic number of li
s. Unfortunately, that doesn't work in IE7, so *float: left
is used (for only IE7 and lower) so that at least they're all on one line - though it still looks horrendous.
padding-left: 5px
應用于每個 li
,然后 li:first-child { padding-left: 0 }
將其移除僅適用于第一個 li
.
padding-left: 5px
is applied to every li
, then li:first-child { padding-left: 0 }
removes it for only the first li
.
#main-nav {
list-style: none;
margin: 0;
padding: 0;
width: 100%;
display: table;
table-layout: fixed;
overflow: hidden
}
#main-nav li {
display: table-cell;
*float: left; /* improve IE7 */
height: 25px;
text-align: center;
padding-left: 5px
}
#main-nav li:first-child {
padding-left: 0
}
#main-nav li a {
width: 100%;
display: block;
height: 100%;
line-height: 25px;
text-decoration: none;
background-color: #e0e0f0;
font-weight: bold;
color: #021020;
}
#main-nav li a:hover {
background-color: #498cd5;
color: #ddeeee;
}
<ul id="main-nav">
<li><a href="#">one</a></li>
<li><a href="#">two</a></li>
<li><a href="#">three</a></li>
</ul>
<hr />
<ul id="main-nav">
<li><a href="#">one</a></li>
<li><a href="#">two</a></li>
<li><a href="#">three</a></li>
<li><a href="#">four</a></li>
<li><a href="#">five</a></li>
</ul>
這篇關于如何創建一個水平菜單,每個項目之間的寬度和間距相等?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!