Search code examples
htmlcsstextalignment

HTML - vertical align at middle


Im trying to make a navigation bar for my website. I want to change the heigth of the bar with its elements.

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
  height: 100px;
}

li {
  float: left;
  vertical-align: middle;
}

li a {
  display: block;
  color: white;
  text-align: center;
  vertical-align: middle;
  text-decoration: none;
}

li a:hover {
  background-color: #111;
}

li form input {
  vertical-align: middle;
}
<ul>
  <li><a class="active" href="#menu">Menu</a></li>
  <li>
    <form>
      <input type="text" name="search" placeholder="Search..">
    </form>
  </li>
</ul>

I tried to align my elements vertically at the middle with the 'align-vertical' tag. It doesn't work. enter image description here


Solution

  • One way to do this is to use padding instead of height on the ul.

    ul {
      list-style-type: none;
      margin: 0;
      padding: 50px 0;
      overflow: hidden;
      background-color: #333;
    }
    
    li {
      float: left;
      vertical-align: middle;
    }
    
    li a {
      display: block;
      color: white;
      text-align: center;
      vertical-align: middle;
      text-decoration: none;
    }
    
    li a:hover {
      background-color: #111;
    }
    
    li form input {
      vertical-align: middle;
    }
    <ul>
      <li><a class="active" href="#menu">Menu</a></li>
      <li>
        <form>
          <input type="text" name="search" placeholder="Search..">
        </form>
      </li>
    </ul>

    Another way it to use flex.

    ul {
    ...
      display: flex;
      align-items: center;
    }
    

    ul {
      list-style-type: none;
      margin: 0;
      padding: 0;
      overflow: hidden;
      background-color: #333;
      height: 100px;
      display: flex;
      align-items: center;
    }
    
    li {
      float: left;
      vertical-align: middle;
    }
    
    li a {
      display: block;
      color: white;
      text-align: center;
      vertical-align: middle;
      text-decoration: none;
    }
    
    li a:hover {
      background-color: #111;
    }
    
    li form input {
      vertical-align: middle;
    }
    <ul>
      <li><a class="active" href="#menu">Menu</a></li>
      <li>
        <form>
          <input type="text" name="search" placeholder="Search..">
        </form>
      </li>
    </ul>