[英]Centering a ul with floated li
I have 我有
<div id="container">
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</div>
With the following CSS: 使用以下CSS:
#container li {
float:left;
height:33px;
line-height:30px;
text-align:center;
width:auto;
}
#container{
width:600px;
}
However I am having difficulty in horizontally centering the ul inside #container
. 但是我很难将
#container
的ul水平居中。 It appears that I need a fixed width set on the ul for margin: 0 auto
to work (needs text-align: center
for IE). 看来我需要在ul上设置一个固定宽度的
margin: 0 auto
工作(需要text-align: center
IE text-align: center
)。 However I do not want to set a fixed width for the ul as the li items will be dynamic. 但是我不想为ul设置固定的宽度,因为li项目是动态的。
Please advise. 请指教。
#container {
width: 600px;
text-align: center;
}
#container ul {
display: inline-block;
}
#container li {
float: left;
height: 33px;
line-height: 30px;
}
Here is a great solution: http://css-tricks.com/centering-list-items-horizontally-slightly-trickier-than-you-might-think/ 这是一个很好的解决方案: http : //css-tricks.com/centering-list-items-horizontally-slightly-trickier-than-you-might-think/
<div id="menu-outer">
<div class="table">
<ul id="horizontal-list">
<li><a href="#"><img src="images/list-item-1.gif" alt="list item 1" /></a></li>
<li><a href="#"><img src="images/list-item-2.gif" alt="list item 2" /></a></li>
<li><a href="#"><img src="images/list-item-3.gif" alt="list item 3" /></a></li>
<li><a href="#"><img src="images/list-item-4.gif" alt="list item 4" /></a></li>
</ul>
</div>
</div>
Now see the very simple CSS that makes it happen: 现在看看实现它的非常简单的CSS:
#menu-outer {
height: 84px;
background: url(images/bar-bg.jpg) repeat-x;
}
.table {
display: table; /* Allow the centering to work */
margin: 0 auto;
}
ul#horizontal-list {
min-width: 696px;
list-style: none;
padding-top: 20px;
}
ul#horizontal-list li {
display: inline;
}
It's the table div that get the job done. 这是完成工作的表格div。 Some days I think "Whatever works."
有些日子我觉得“无论什么都有用”。 should be the slogan for CSS.
应该是CSS的口号。
in css : 在css中:
ul {
float: left;
}
jquery jQuery的
centerize = function(){
var parentWidth = $("ul").parent("#container").width();
var width = $("ul").width();
var dif = (parentWidth - width) / 2;
$("ul").css("margin-left", dif + "px");
};
centerize();
probably u need to work for every browser zoom, so add : 可能你需要为每个浏览器缩放工作,所以添加:
$(window).resize(function(){
centerize();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.