TerryJ26
TerryJ26

Reputation: 63

Vertically Aligning all elements in my list

I have a navbar using Ul and Li elements. I have everything styled the way I want it besides the vertical factor. I want all elements to be vertically centered but it doesn't work. I tried using vertical-align: middle; on the elements but it did nothing.

Here's my code.

nav {
  background-color: #4D0066;
  width: 400px;
  height: 60px;
  border: 3px solid black;
  border-radius: 5px 5px 35px 35px;
  ;
  margin: 5px auto;
}

ul {
  font-size: 0;
  text-align: center;
}

li, li a:after {
  display: inline-block;
  vertical-align: middle;
}
li a:after {
  content:'';
  height: 100%;
}

a {
  color: white;
  text-decoration: none;
  font-size: 15pt;
  display: block;
  padding: 0 10px;
}

.home {
  width: 32px;
  display: block;
  vertical-align: middle;
}
<nav>
  <ul>
    <li><a href="#">Roster</a></li>
    <li><a href="#">News</a></li>
    <li>
      <a href="#"><img src="images/home.png" class="home"></a>
    </li>
    <li><a href="#">Arena</a></li>
    <li><a href="#">Leagues</a></li>
  </ul>
</nav>

Upvotes: 2

Views: 37

Answers (1)

Matthew Varga
Matthew Varga

Reputation: 404

To align the li items within the ul. You should set the display of ul to flex, and either apply align-items:center or align-items:baseline. Center will vertically center them, baseline will align them with eachother.

Setting the height to 100% will also make sure it takes up the entire space provided.

For more on flexbox see: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

nav {
  background-color: #4D0066;
  width: 400px;
  height: 60px;
  border: 3px solid black;
  border-radius: 5px 5px 35px 35px;;
  margin: 5px auto;
}

ul {
  font-size: 0;
  text-align: center;
  display:flex;
  align-items: center;
  height: 100%;
}

li {
  display: inline-block;
}

a {
  color: white;
  text-decoration: none;
  font-size: 15pt;
  display: block;
  padding: 0 10px;
}

.home {
  width: 32px;
  display: block;
  vertical-align: middle;
}
<nav>
  <ul>
    <li><a href="#">Roster</a></li>
    <li><a href="#">News</a></li>
    <li><a href="#"><img src="images/home.png" class="home"></a></li>
    <li><a href="#">Arena</a></li>
    <li><a href="#">Leagues</a></li>
  </ul>
</nav>

Upvotes: 1

Related Questions