Search code examples
htmlcsstwitter-bootstrapnavbarcentering

Cannot properly centre nav bar (uses col-md-3) bootstrap css and html


so basically I've got this code: HTML and CSS below, using bootstrap as well, and for some reason, it's not centred. It used to be, but at some point it wasn't anymore, now it pulls to the left. See image below. Any ideas?

<div class="row" id="nav-bar">
    <div class="col-md-9">
        <ul>
            <li class="col-md-3 nav-btn" id="home"><a href="index.html">Home</a></li>
            <li class="col-md-3 nav-btn" id="about"><a href="about.html">About</a></li>
            <li class="col-md-3 nav-btn dropdown-toggle" id="games">
                <a href="#">Games & Apps &#9660;</a>
                <div class="dropdown">
                    <ul>
                        <li><a href="#" id="games2">Games & Apps &#9660;</a></li>
                        <li id="first"><a href="#">Space Rodeo</a></li>
                        <li id="spaced"><a href="#">Boodya's Carpet Ride</a></li>
                        <li id="spaced"><a href="#">Ultimate Points Counter</a></li>
                    </ul>
                </div>
            </li>
            <li class="col-md-3 nav-btn" id="blog"><a href="blog.html">Blog</a></li>
        </ul>
    </div>                              
</div>

#nav-bar {
margin: 0px 0px 10px 0px;  
height: 60px;
}

#nav-bar ul {
    margin-top: 20px;   
}

.col-md-3 a {
    padding: 15px 40px 15px 40px;
    font-size: 20px;
    text-decoration: none;
    text-align: center;
    color: #B6B6B6;
}

#nav-bar a:hover {
    color: #428bca;
}

.col-md-3 {
    display: inline;   
}

.col-md-9 {
    float: none;
    margin: auto;
    left: 0;
    right: 0;
}

.dropdown {
    padding: 0;
    margin-top: -48px;
    position: absolute;
    z-index: 10;
    background-color: #ffffff;
    box-shadow: -5px -5px 20px;
    border-radius: 5px;
    height: 210px;
    width: 275px;
}

.dropdown ul {
    padding: 0;
    margin-top: 0;
}

.dropdown li {
    list-style: none;
    padding: 0;
    width: 310px;
}

#games2 {
    color: #428bca;
}

#spaced {
    margin-top: 10px;   
}

#first {
    padding-top: 20px;
    border-top: 1px solid black;
    margin-top: 22px;
} 

Showing result of code, the navbar is off centre

https://i.sstatic.net/smtTP.png


Solution

  • Your list items are display: inline which means they'll follow the alignment rules of text. Since you set no text-align, it defaults to the left. You can fix that by adding text-align: center to your ul so the contents will be centered.

    Now the insides of the dropdown will also inherit that, you can reset that by setting text-align: left back on the dropdown ul again.

    Also reset the left padding that ul has by default.

    #nav-bar ul {
        padding-left: 0;
        text-align: center;
    }
    
    #nav-bar .dropdown  ul {
         text-align: left;   
    }
    

    Works in this jsFiddle