简体   繁体   中英

Center list in div (for navigation bar)

Going off of the note at the top of this tutorial ( http://css-tricks.com/centering-list-items-horizontally-slightly-trickier-than-you-might-think/ ), I tried to center a list of two links in the page, but it is centering only the first list item, not the entire list.

li{
    font-family: Futura, Arvo, sans-serif;
    display: inline-block;
}
ul{
    text-align: center;
}

div#nav-list {

    left: 0;
    right: 0;
    margin-right: auto;
    margin-left: auto;

    width: auto;
    height: auto;
    background: #E8E8E8;
}

"nav-list" is the container for the navigation bar, shown in the picture colored grey.

Here is the issue- you can see that "about" is centered, but not the entire list. 在此处输入图片说明

Thanks in advance! Edit: Here's the HTML:

<div id="center_content">
    <h1 id="page-heading">Title</h1>
    <hr id="first-rule"></hr>
    <div id="nav-list">
        <ul>
            <li>about</li> <li>work</li> 
        </ul>
    </div>
    <hr></hr>
    <p>Here is a paragraph. </p>
</div>

Remove the list padding. By default, list have a 40px padding-left. Try to use ul{ padding:0; } ul{ padding:0; }

Try apply these styles :

ul { 
    margin: 0 auto;
    padding: 0;
    text-align: center;
    width: 170px; /*as per your need*/
}

Hows this for you: http://jsfiddle.net/theStudent/6UnNs/

CSS

li {
    font-family: Futura, Arvo, sans-serif;
    display: inline-block;
    padding: 10px;
}

ul {
    text-align: center;
    background:red;
    width: 25%;
    margin:0 auto;
}
ul li:first-child {

    background:#ccc;
    display:block;
    margin:0 0 0 -40px;
}

HTML

<ul>
    <li>TITLE</li>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 2</li>
</ul>

Just play with settings I added some color so you can see

try this

<div>
<ul>
    <li>one</li>
    <li>two</li>
    <li>three</li>
</ul>

div ul li{float:left;list-style:none;margin:0 10px}
div ul{display: inline-block;margin: 0 auto;}
div{text-align:center}

JSFiddle

Here you go:

1) Set text-align: center; on the nav-list element

2) Set d isplay: inline-block on the list

FIDDLE

li {
    font-family: Futura, Arvo, sans-serif;
    display:inline-block;
    padding: 0 10px;
}
ul{

    list-style: none;
    display: inline-block;
    padding:0;
}

div#nav-list {

    text-align: center;
    background: #E8E8E8;
}

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