简体   繁体   中英

Horizontal Centered Menu in CSS?

I want to make a horizontal centered menu. I have tried using things like text align center and margin auto but can't get them to work. I do not want to use a table.

Here's my code:

<footer class="container">
    <div class="row">
        <div class="span12">
            <ul>
                <li>footer info 1</li>
                <li>footer info 2</li>
                <li>footer info 3</li>
            </ul>
        </div>
    </div>

With the provided HTML:

ul { text-align: center; }
li { display: inline-block; } /* Don't float them */

http://jsfiddle.net/NpLR3/

The following will work without using text-align :

footer {
    width: 100%;
}
.row {
    position: absolute;
    left: 50%;
}
.span12 {
    position: relative;
    left: -50%;
}
ul {
    padding: 0;
}
li {
    display: inline;
    list-style: none;
    margin-left: 1em;
}
li:first-child {
    margin-left: 0;
}

The important bits are:

(1) that the outer container for the menu has 100% width,

(2) that the inner container is absolutely positioned at 50% left (which positions the left side of the menu at the center of the page), and

(3) that the menu is then relatively positioned at -50% left (moving it back to the left half its width, so that the center of the menu is now at the center of the page).

The other stuff is just cosmetic.

See working example .

Demo

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

See http://jsfiddle.net/aCSgz/

Basically you need to set the ul and li to display: block.

ul { display: block; text-align:center; }
ul li { display: block; }

You need to set the display property on the LIs to inline-block and set the text-align on the UL to center .

HTML:

<footer class="container">
    <div class="row">
        <div class="span12">
            <ul>
                <li>footer info 1</li>
                <li>footer info 2</li>
                <li>footer info 3</li>
            </ul>
        </div>
    </div>
</footer>

CSS:

footer {
    background:#fdd;
}
div.row {
    background: #dfd;
}
ul {
    background: #ddf;
    list-style: none;
    margin: 0;
    padding: 0;
    text-align: center;
}

li {
    display: inline-block;
    background: #fff;
    margin: 0.5em;
    padding: 0.5em;
}

http://jsfiddle.net/ghodmode/h2gT3/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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