Why is my navbar overflowing my page width?

Viewed 39

I am trying to make a product landing page for freecodecamp, my navbar (the first thing I have to do) isn't coming out well. What is wrong with my code?

Also I want to put a image behind the navbar.navbar

It's a bit frustrating coding, how do you learn with all these gimmicky little things going the wrong way? I find I have to have someone here to make sure the code is explained, but sincerely I don't have that luxury.

<div class="nav-bar-wrapper">
       <nav id="nav-bar">
          <ul>
            <li><a class="nav-link" href="#">link1</a></li>
            <li><a class="nav-link" href="#">link2</a></li>
            <li><a class="nav-link" href="#">link3</a></li>
            <li><a class="nav-link" href="#">link4</a></li>
          </ul>
        </nav>
</div>


    html{
         width: 100%; 
         height: auto;
    }

    .nav-bar{
       width: 100%;
       height: 7vh;
       background-color: #555; 
    }
    #nav-bar a.active {
       background-color: #04AA6D; 
    }
    .nav-link{
       text-decoration: none;
       padding: 3px;
       display: inline-block;
       color: coral;
       width: 25%;
     }
    .ul, li{
       display:inline-block;
     } 
   ul{
       display: inline;
       text-align: center;
       padding:10px;
       border: 3px solid;
       font-size: 20px;
       text-align: justify;
    }
    li{
        margin: auto;
        display: inline;
    }
    .nav-link:hover{
         color: green;
    }
  
2 Answers

This is because of you set for all item width of 25%. You want to be all the same size in full of width of screen. But all of it has margin, padding, border and etc so you don't extualy has 100% space, you have maybe 98%. So if you change it to 24% or 23% will be like that.

.nav-link{
       width: 23%;
}

A better practice is to use flex.For flex you just need to set:

  html{
         width: 100%; 
         height: auto;
    }

    .nav-bar{
       width: 100%;
       height: 7vh;
       background-color: #555; 
    }
    #nav-bar a.active {
       background-color: #04AA6D; 
    }
    .nav-link{
       text-decoration: none;
       padding: 3px;
       display: inline-block;
       color: coral;
       width: 100%;
     }
    .ul, li{
       display:inline-block;
     } 
   ul{
       display: flex;
       text-align: center;
       padding:10px;
       border: 3px solid;
       font-size: 20px;
       text-align: justify;
    }
    li{
        margin: auto;
        display: inline;
    }
    .nav-link:hover{
         color: green;
    }
<div class="nav-bar-wrapper">
       <nav id="nav-bar">
          <ul>
            <li><a class="nav-link" href="#">link1</a></li>
            <li><a class="nav-link" href="#">link2</a></li>
            <li><a class="nav-link" href="#">link3</a></li>
            <li><a class="nav-link" href="#">link4</a></li>
          </ul>
        </nav>
</div>

Related