問題描述
我想在一個 900 像素的容器上均勻地拉伸 6 個導航項,并且在它們之間留有均勻的空白空間.比如……
I'd like to stretch 6 nav items evenly across a 900px container, with an even amount of white space between. For instance...
---| 900px Container |---
---| HOME ABOUT BASIC SERVICES SPECIALTY SERVICES OUR STAFF CONTACT US |---
目前,我能找到的最佳方法如下:
Currently, the best method I can find to do this is the following:
nav ul {
width: 900px;
margin: 0 auto;
}
nav li {
line-height: 87px;
float: left;
text-align: center;
width: 150px;
}
這個問題有兩個方面.首先,它并沒有真正證明它的合理性,而是將 li 標簽均勻地分布在整個 ul 標簽中.在較小的菜單項(例如HOME"或ABOUT")和較大的菜單項(例如BASIC SERVICES")之間創建不均勻的空白區域.
The PROBLEM with this is two fold. First of all, it doesn't truly justify it, but rather spreads the li tags evenly throughout the ul tag.. creating uneven white-space between smaller menu items like "HOME" or "ABOUT" and larger ones like "BASIC SERVICES".
第二個問題是,如果導航項目大于 150 像素,則布局會中斷,專業服務就是這樣 - 即使整個導航有足夠的空間.
The second problem is that the layout breaks if a nav item is larger than 150px, which SPECIALTY SERVICES is - even though there is more than enough space for the whole nav.
誰能幫我解決這個問題?我一直在網上搜索解決方案,但它們似乎都不夠用.僅在可能的情況下使用 CSS/HTML...
Can anyone solve this for me? I've been scouring the web for solutions, and they all seem to come up short. CSS / HTML only if possible...
謝謝!
更新(2013 年 7 月 29 日):使用 table-cell 是實現此布局的最佳現代方式.請參閱下面菲利克斯的回答.table cell
屬性目前適用于 94% 的瀏覽器.您必須對 IE7 及以下版本做一些事情,否則應該沒問題.
UPDATE (7/29/13): Using table-cell is the best modern way to implement this layout. See felix's answer below. The table cell
property works on 94% of browsers currently. You'll have to do something about IE7 and below, but otherwise should be ok.
更新(2013 年 7 月 30 日):不幸的是,如果您將此布局與媒體查詢結合使用,則會有一個 webkit 錯誤會影響這一點.現在,您必須避免更改顯示"屬性.查看 Webkit 錯誤.
UPDATE (7/30/13): Unfortunately, there is a webkit bug that impacts this if you're combining this layout with Media Queries. For now you'll have to avoid changing the 'display' property. See Webkit Bug.
更新(2014 年 7 月 25 日):下面有一個更好的解決方案,現在涉及 text-align: justify.使用它更簡單,您將避免 Webkit 錯誤.
UPDATE (7/25/14): There is a better solution to this below now involving text-align: justify. Using this is simpler and you'll avoid the Webkit bug.
推薦答案
在容器上使用 text-align:justify
,這樣無論列表中有多少元素它都可以工作(您不必計算每個列表項的 % 寬度
Use text-align:justify
on the container, this way it will work no matter how many elements you have in your list (you don't have to work out % widths for each list item
#nav {
text-align: justify;
min-width: 500px;
}
#nav:after {
content: '';
display: inline-block;
width: 100%;
}
#nav li {
display: inline-block;
}
<ul id="nav">
<li><a href="#">HOME</a></li>
<li><a href="#">ABOUT</a></li>
<li><a href="#">BASIC SERVICES</a></li>
<li><a href="#">OUR STAFF</a></li>
<li><a href="#">CONTACT US</a></li>
</ul>
FIDDLE
這篇關于如何在指定容器中均勻且完全地拉伸固定數量的水平導航項的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!