Search code examples
htmlcssvertical-alignment

CSS Navigation Vertical Align


I am unaware of the best practice to get my desired result. I have used tables here which have got me close to what I want.

The result doesn't have vertically centered text and I cannot figure out how. Tried using UL to get this but had no luck:

#hotspotbg table {
  margin-top: 1px;
}
#hotspotbg table tr td {
  border-right: 1px solid #ccc;
  border-left: 1px solid #ccc;
}
#hotspotbg table tr td a {
  text-align: center;
  text-decoration: none;
  display: block;
  font-family: Tahoma, Geneva, sans-serif;
  color: #fff;
  height: 51px;
}
#hotspotbg table tr td a:hover {
  background: #FFF;
  color: #000;
}
<table width="900" height="51px" border="0" cellspacing="0" cellpadding="0" align="center">
  <tr>
    <td width="25%" height="51" valign="middle"><a href="#">Home</a>
    </td>
    <td width="25%"><a href="#">Products</a>
    </td>
    <td width="25%"><a href="#">Reviews</a>
    </td>
    <td width="25%"><a href="#">Contact</a>
    </td>
  </tr>
</table>


Solution

  • Setting the line-height of the child (a element in your case) to the height of the parent, will vertically align the text of the a element. See below for more information.

    .wrapper {
        height: 70px;
        width: 100%;
        background: red;
        overflow: hidden;
    }
    
    .wrapper a {
        /*NOT AFFECTING THE VERTICAL ALIGN*/
        display: block;
        float: left;
        height: 70px;
        width: 50%;
        color: #fff;
        text-align: center;
        /*AFFECTING VERTICAL ALIGN*/
        line-height: 70px;
    }
    <div class="wrapper">
        <a href="#">test</a>
        <a href="#">nice</a>
    </div>