htmlcssflexboxalignmentjustify

Can't get justify-content and align-items to work on my header and navigation bar at the same time


I'm trying to make a header bar with navigation links for the first time using flexbox. When I apply display: flex to the header element in CSS, in an attempt to vertically align the logo and links, the navigation links become no longer spaced out (see the link to see this). However if I remove the display:flex and align-items from the header element in CSS, the navigation links become spaced out but then aren't vertically aligned. I can't get both to happen (ie. be spaced out AND aligned vertically) at the same time. I have tried many combinations but can't figure out if some things are conflicting each other! Might be easier to look at my work here:

https://codepen.io/ellie1/pen/mdPomWN

Or my html and css respectively below. Thanks in advance!

<header id='header-img'>
  <div class='logo1'>
    <img id='logo'
       src='https://www.clipartkey.com/mpngs/m/61-614698_transparent-headphones-clipart-png-gaming-headset-silhouette.png'/>
  </div>

  <nav id='nav-bar'>
    
    <ul>  
      <li> <a href='' class='nav-link'> Features </a> </li> 
      <li> <a href='' class='nav-link'> Colours </a> </li> 
      <li> <a href='' class='nav-link'> Pricing </a> </li>
    </ul>
       
       </nav>
  
</header>

html{
  font-size= 10px;
}

body{
  background-color: #F7F7F7;
  font-family: system-ui;
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

header{
  position: fixed;
  min-height: 75px;
  padding: 0px 20px;
  background-color: #212529;
  width: 100%;
  height: 90px;
  display: flex;
  align-items: center;
}

li{
  list-style: none;
}


nav> ul{
  display: flex;
  flex-direction: row;
  justify-content: space-evenly;

}

a{
  font-size: 1.2rem;
  font-weight: bold;
  text-decoration: none;
  color: #b51b20;
}

 img{
  width: 6%;
  height: auto;
  padding-top: 5px;
  display: flex;
  border-radius: 20px;

}




Solution

  • I recommend you to use classes only, but I realize this is for flex-learning purposes only so it's ok for now.

    To make your workday a bit easier, you can try and use the Inspect Element feature (I find chrome inspect element as the best but any other is fine too).

    The reason why I recommend this feature is because it makes stuff easier to "debug" and to solve.

    For example, in your case, when you Inspect element on the tag, you can see this:

    inspect element of the nav tag

    You can see the width of the nav tag.

    You try to justify-between, and it actually works but your problem is the width of the nav tag, If you'll give the nav tag 100% width, it will work.

    A working example:

    #nav-bar {
        width: 100%;
    }
    

    https://codepen.io/aviv-day/pen/KKzExGw

    Again, there is a better way to write the code you're trying to achieve. Try watching some Flexbox tutorials. I recommend netninja videos on youtube.