Search code examples
htmlcssnavbarnav

How do I make a horizontal centered navbar that doesn't stretch the whole page?


I've been wanting to make a horizontal navbar that doesn't stretch the whole page. Ended up following a tutorial on how to make a navbar that is really similar to what I have in mind (https://cssdeck.com/blog/super-simple-horizontal-navigation-bar/), the only problem is that it isn't centered and the background matches the whole page in width, which I don't want.I uploaded a sketch image of how I want the navbar to appear. enter image description here

The code on the site is as follows:

HTML

<ul id="nav">
    <li><a href="#">About Us</a></li>
    <li><a href="#">Our Products</a></li>
    <li><a href="#">FAQs</a></li>
    <li><a href="#">Contact</a></li>
    <li><a href="#">Login</a></li>
</ul>

CSS

#nav {
    width: 100%;
    float: left;
    margin: 0 0 3em 0;
    padding: 0;
    list-style: none;
    background-color: #f2f2f2;
    border-bottom: 1px solid #ccc; 
    border-top: 1px solid #ccc; }
#nav li {
    float: left; }
#nav li a {
    display: block;
    padding: 8px 15px;
    text-decoration: none;
    font-weight: bold;
    color: #069;
    border-right: 1px solid #ccc; }
#nav li a:hover {
    color: #c00;
    background-color: #fff; }

I tried creating a div which encapsulates the unordered list, made its width 40% of the page, centered it using margin-left: auto and margin-right: auto. Then I specified each list item to be 25% of the parent element (which is the div since I didn't specify width for the unordered list element itself), as I want 4 list items to be on the navbar (100/4 = 25). And so, I hope that by making some changes to the tutorial code I found online, I can learn how to modify my own code.

Really hope someone can help me, thanks in advance!


Solution

  • I made some CSS changes which will solve your issue:

    #nav {
      width: auto;
      margin: auto;
      padding: 0;
      list-style: none;
      background-color: #f2f2f2;
      border: 1px solid #ccc; 
      display: table;
      }
    #nav li {
      float: left; }
    #nav li a {
      display: block;
      padding: 8px 15px;
      text-decoration: none;
      font-weight: bold;
      color: #069;
      border-right: 1px solid #ccc; }
    #nav li a:hover {
      color: #c00;
      background-color: #fff; }
    #nav li:last-child a{border: none;}
    <ul id="nav">
            <li><a href="#">About Us</a></li>
            <li><a href="#">Our Products</a></li>
            <li><a href="#">FAQs</a></li>
            <li><a href="#">Contact</a></li>
            <li><a href="#">Login</a></li>
        </ul>