开发者

Horizontally Centre a UL inside a DIV

开发者 https://www.devze.com 2023-03-22 12:33 出处:网络
I have a div with a ul inside, I want to center the ul horizontally of the screen. The full code of the project can be found here: jsfiddle

I have a div with a ul inside, I want to center the ul horizontally of the screen.

The full code of the project can be found here: jsfiddle

I have tried using:

margin: 0 auto; /* After setting the width of course */
text-align: center; /* Ran out of ideas!! */

I also tried relative positioni开发者_如何学JAVAng and setting % instead of px, but this doesnt give me exact centre of the screen, and also, if I added more items to the menu, it would'nt be center after including them items (using a %).

My FULL code is in jsfiddle for all you to tinker with.

I have pasted some of the (what I think is) relevant code below for your convenience:

CSS:

/* Main*/
ul#nav { 
display: inline-block;
padding: 0px; 
list-style-type: none; 
white-space: nowrap;
position: relative;
top: 10px;
left: 10%; /* This is what im currently using, but as thought, it doesnt work as needed :(*/
border: 2px solid chocolate;
-moz-border-radius: 10px; /* Border Radius for Mozilla Firefox */
border-radius: 10px;      /* Border Radius for everything else*/
}

ul#nav li { 
float: left; 
font-family: 'Myraid Pro', Arial, Helvetica, sans-serif;  /*Use available font for menu */
font-weight: bold; 
margin: 0; 
padding: 5px 0 4px 0; 
background-color: #ee8043; /*Background Colour for the <li>*/
padding: 5px;              /* Padding for the LI */
-moz-border-radius: 8px; /* Border Radius for Mozilla Firefox */
border-radius: 8px;      /* Border Radius for everything else*/

}

HTML:

        <div id="header">
        <a href="index.html"><img id="logo" src="images/Dafne_Logo.png"/></a>

        <div id="navbar">
            <ul id="nav">
                <li><a href="index.html" rel="home">Home</a></li>
                <li class="menu_separator">|</li>
                <li><a href="index.html">News</a></li>
                <li class="menu_separator">|</li>
                <li><a href="forums.html">Forums</a></li>
                <li class="menu_separator">|</li>
                <li><a href="signup4327.html?to=%252F">Signup</a></li>
                <li class="menu_separator">|</li>
                <li><a href="login4327.html?to=%252F">Login</a></li>
                <li class="menu_separator">|</li>
            </ul>
        </div>

    </div>

    <div id="coloured_bar"></div>


So basically, I want to center the #nav which is contained within the #navbar, which is contained within the #header.


Adding text-align:center to the #navbar div should do it because your list is inline-block.

You'll have to remove the left:10% if you want it centered.


Here you go: http://jsfiddle.net/gzB6a/ I added

div#navbar {
  text-align: center;
}

And removed

the ul#nav { left: 5%; }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号