Home > Software engineering >  How to fully center a nav bar using flexbox
How to fully center a nav bar using flexbox

Time:03-23

Still quite a newbie and would appreciate some guidance as this keeps happening on my projects.

I create a nav bar using display: flex - I think I have center aligned everything, but it's moving off to the right.

I was expecting the nav to be center aligned because of the following properties.

.navlist {
  display: flex;
  justify-content: center;
}

.navlist li {
  padding: 20px;
  list-style-type: none;
  text-align: center;
}

But I get slightly off centre result

Please check my codepen

I've also tried margin: auto but still can't figure it out!

Thanks in advance

CodePudding user response:

Add the following code in your CSS and it should work fine.

.navlist li:first-child {padding-left: 0;}

The reason your nav is a little off-center is that it is adding left padding of 20px based on your code so the nav shifts 20px towards the right.

Hope this answer is helpful!

CodePudding user response:

Added a slight change to your code, see if it is what you're expecting

.navlist {
  display: flex;
  justify-content: center;
  text-align: center;
  padding-left: 0;
}
  • Related