Html 拉伸水平 ul 以适应 div 的宽度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5186712/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Stretch horizontal ul to fit width of div
提问by Glenn
For the main nav of my site, there is a 980px wide div with a ul for the main nav links. I am trying to make the nav links stretch to fit the width of the div evenly.
对于我网站的主导航,有一个 980 像素宽的 div,主导航链接有一个 ul。我试图使导航链接拉伸以均匀地适应 div 的宽度。
<div style="width: 980px;">
<ul id="horizontal-style">
<li><a href="#">Nav Item</a></li>
<li><a href="#">Short Item</a></li>
<li><a href="#">Really Long Nav Item</a></li>
<li><a href="#">Nav Link</a></li>
<li><a href="#">Another Link</a></li>
</ul>
</div>
I am doing some typical css to make the ul list horizontally (float: left, display: block). I can tweak the padding of the li to get it very close, but what I really need is a way to make it stretch to fit automatically. Possible?
我正在做一些典型的 css 来水平制作 ul 列表(浮动:左,显示:块)。我可以调整 li 的填充以使其非常接近,但我真正需要的是一种使其自动拉伸以适应的方法。可能的?
EditDifficulty 1: Can't use tables. Difficulty 2: Each nav item will be a different width to accommodate longer and shorter link names.
编辑难点1:不能使用表格。难点 2:每个导航项都有不同的宽度,以适应更长和更短的链接名称。
回答by thirtydot
This is the easiest way to do it: http://jsfiddle.net/thirtydot/jwJBd/
这是最简单的方法:http: //jsfiddle.net/thirtydot/jwJBd/
(or with table-layout: fixed
for even width distribution: http://jsfiddle.net/thirtydot/jwJBd/59/)
(或table-layout: fixed
均匀宽度分布:http: //jsfiddle.net/thirtydot/jwJBd/59/)
This won't workin IE7.
这在 IE7 中不起作用。
#horizontal-style {
display: table;
width: 100%;
/*table-layout: fixed;*/
}
#horizontal-style li {
display: table-cell;
}
#horizontal-style a {
display: block;
border: 1px solid red;
text-align: center;
margin: 0 5px;
background: #999;
}
Old answer before your edit: http://jsfiddle.net/thirtydot/DsqWr/
编辑前的旧答案:http: //jsfiddle.net/thirtydot/DsqWr/
回答by Shad
People hate on tables for non-tabular data, but what you're asking for is exactly what tables are good at. <table width="100%">
人们讨厌表格中的非表格数据,但您要求的正是表格所擅长的。 <table width="100%">
回答by gailbear
inelegant (but effective) way: use percentages
不优雅(但有效)的方式:使用百分比
#horizontal-style {
width: 100%;
}
li {
width: 20%;
}
This only works with the 5 <li>
example. For more or less, modify your percentage accordingly. If you have other <li>
s on your page, you can always assign these particular ones a class of "menu-li" so that only they are affected.
这仅适用于 5<li>
示例。或多或少,相应地修改您的百分比。如果您<li>
的页面上有其他s,您始终可以为这些特定的 s 分配一类“菜单-li”,以便只有它们受到影响。