简体   繁体   English

将水平列表显示为块

[英]Displaying a horizontal list as a block

I have a horizontal unordered list I want to center horizontally in a div container (that's arbitrarily bigger than the list). 我有一个水平的无序列表,我想在div容器中水平居中(比列表大得多)。 I was thinking of displaying the ul as a block and using auto margins to center the list within its parent container. 我当时想将ul显示为一个块,并使用自动边距将列表置于其父容器内。 But... I can't seem to get the ul to display as a block and not take 100% width. 但是...我似乎无法让ul显示为一个块并且不采用100%的宽度。

From what I understand, block elements take the required width to wrap around children elements (unless they're uncleared floats or absolute positionned), so I would think that placing the ul and li's as blocks should do the trick. 根据我的理解,块元素采用所需的宽度来包裹子元素(除非它们是未清除的浮点数或绝对位置),因此我认为将ul和li放置为块应该可以解决问题。 Unfortunately it doesn't and I don't understand why. 不幸的是,事实并非如此,我也不知道为什么。

Any idea? 任何想法?

Here's the code: http://jsfiddle.net/kccbg/1/ 这是代码: http : //jsfiddle.net/kccbg/1/

Try using display: inline-block instead, and setting text-align: center for the container like so: 尝试使用display: inline-block代替,并为容器设置text-align: center ,如下所示:

HTML: HTML:

<div class="container">
    <ul>
        <li>Item 1</li>
        <li>Item 1</li>
        <li>Item 1</li>
        <li>Item 1</li>
        <li>Item 1</li>
    </ul>
</div>​

CSS: CSS:

.container{
    width:100%;
    background-color:#CCC;
    height:20px;
    text-align: center;
}
ul{
    display:inline-block;
    margin:0 auto;
}
li{
    display:inline-block;
}

Example

UPDATE: (based on comment from gmeben) 更新:(基于来自gmeben的评论)

Change the css to: 将CSS更改为:

.container{width:100%; background-color:#CCC; text-align:center}
li{display:inline;}

and remove 并删除

<li class="clear"></li>

from html. 来自html。

No floats and clearing and no inline-block (not supported/rendered-correctly by all browsers). 没有浮点数和清除数,也没有内联代码块(并非所有浏览器都支持/正确渲染)。

If you know the total width of your list items, you can set the width of the <ul> and then set its margin to 0 auto. 如果知道列表项的总宽度,则可以设置<ul>的宽度,然后将其边距设置为0 auto。 jsFiddle example . jsFiddle示例

CSS CSS

.container{
    width:100%; 
    background-color:#CCC; 
    height:20px;
}
ul{
    list-style:none;
    width:200px;
    margin:0 auto;
}
li{
    float:left; 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM