Home > Net >  How to align some elements of a navigation bar in CSS?
How to align some elements of a navigation bar in CSS?

Time:10-14

I am making a navigation bar using HTML and CSS. I have 3 elements: 2 a-href and 1 button

HTML:

  <nav>
    <ul>
      <li>
        <a href="/signin">Home</a>
      </li>
      <li>
        <a href="/games">Games</a>
      </li>
      <button class="btn-item btn-ghost red secundary round">
        Sign Out
      </button>
    </ul>
    <div class="hide"><i class="fa fa-bars" aria-hidden="true"></i> Menu</div>
  </nav>

and I have these styles:

CSS:

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: monospace;
  font-size: 20px;
}

nav ul {
  list-style: none;
  background: black;
  text-align: left;
}


nav ul li {
  display: inline-block;
  padding: 20px;
  transition: all ease-in-out 250ms;
}

ul li a {
  color: white;
  text-decoration: none;
}

nav ul li:hover {
  background: red;
}

specifically this block:

nav ul {
  list-style: none;
  background: black;
  text-align: left;
}

in the text-align: left property, it is in charge of aligning all the elements of the navigation bar, the problem is that I want the a href to be aligned to the center and the button to the right. How can I achieve this?

CodePudding user response:

Try this:

`nav ul {
          list-style: none;
          background: black;
          text-align: center;
        }`

Pretty much just changing the text align to center instead of left, this is the results.

enter image description here

CodePudding user response:

Sorry about the late response, just add

button{
  float: right;
  margin-top:15px;
} 

I'm using code pen so you may have to adjust the margin top to fit whatever view you have. Let me know if you have any other questions.

CodePudding user response:

Try this out. Made the nav tag the main container instead of the ul, and did some other things.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: monospace;
  font-size: 20px;
}

nav {
  background: black;
  width: 100vw;
  height: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
}

nav ul {
  list-style: none;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 90%;
}

nav ul li {
  display: inline-block;
  padding: 20px;
  transition: all ease-in-out 250ms;
}

ul li a {
  color: white;
  text-decoration: none;
}

nav ul li:hover {
  background: red;
}
  <nav>
    <ul>
      <li>
        <a href="/signin">Home</a>
      </li>
      <li>
        <a href="/games">Games</a>
      </li>
    </ul>
    <button id="myButton" class="btn-item btn-ghost red secundary round">
      Sign Out
    </button>
    <!-- <div class="hide"><i class="fa fa-bars" aria-hidden="true"></i> Menu</div> -->
  </nav>

  • Related