skip to Main Content

I am currently creating a navbar for my personal website, in the process of making it look decent on mobile I can’t seem to center the navbar properly. It leans to the right no matter what I do.As you can see, it does not align with the pink box above (which is centered correctly)

Here is my code for the navbar. I have tried margin and padding properties but they do not have an affect at all inside the @media property. I had also previously made the navbar with flexbox and I ran into the same issue where it leans to the right. I have changed the display to flex INSIDE the @media property and it also leans to the right and neither margin nor padding affect it at all.

.navbar {
  padding: 1px 2px;
  border: 4px double;
  justify-content: center;
  margin-left: 43%;
  margin-right: 43%;
  border-radius: 8px;
  background-color: rgba(19, 19, 22, 0.7);
  border-color: white;
}

.navbar ul {
  list-style: none;
  text-align: center;
  margin: 0;
  padding: 0;
}

.navbar li {
  display: inline-block;
  margin: 3px 13px;
}

@media (max-width: 500px) {
  .navbar {
    width: fit-content;
  }
  .navbar ul {
    text-align: center;
  }
}
<nav class="navbar">
  <ul>
    <li><a href="index.html">Home</a></li>
    <li><a href="about.html">About</a></li>
    <li><a href="contacts.html">Contacts</a></li>
  </ul>
</nav>

In my @media I have the width:fit-content property however if I remove it, it doesn’t lean to the right anymore but the text overlaps the border.

2

Answers


  1. remove margins on navbar. put following on navbar’s parent:

      display: flex;
      justify-content:center;
      align-items:center;
    
    Login or Signup to reply.
  2. I’ve made some changes to your navbar. First, I wrapped it inside a div with the class d-flex justify-content-center. This helps to center it properly on the page. Then, I removed margins from the navbar class and also removed the @media CSS. Now, your navigation bar should be nicely centered and look good on mobile devices too.

    .navbar {
      padding: 1px 2px;
      border: 4px double;
      border-radius: 8px;
      background-color: rgba(19, 19, 22, 0.7);
      border-color: white;
    }
    
    .navbar ul {
      list-style: none;
      text-align: center;
      margin: 0;
      padding: 0;
    }
    
    .navbar li {
      display: inline-block;
      margin: 3px 13px;
    }
    
    .d-flex {
      display: flex;
    }
    .justify-content-center {
      justify-content: center;
    }
    <div class="d-flex justify-content-center">
      <nav class="navbar">
        <ul>
          <li><a href="index.html">Home</a></li>
          <li><a href="about.html">About</a></li>
          <li><a href="contacts.html">Contacts</a></li>
        </ul>
      </nav>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search