Sam Sam - 6 months ago 10
HTML Question

vertically center text in navigation bar

I am trying to make a navigation bar in which the buttons' text will be aligned in the center vertically.

Currently, everything is working fine with the navigation bar besides the vertical align.

I have tried many methods such as with line height, padding to the top and bottom (messes up my heights so the text divs overflow), flex, and table display.



html,
body {
height: 100%;
margin: 0px;
}
#nav {
height: 10%;
background-color: rgb(52, 152, 219);
position: fixed;
top: 0;
left: 0;
width: 100%;
color: white;
font-family: Calibri;
font-size: 200%;
text-align: center;
display: flex;
}
#nav div {
display: inline-block;
height: 100%;
align-items: stretch;
flex: 1;
}
#nav div:hover {
background-color: rgb(41, 128, 185);
cursor: pointer;
}

<div id="main">
<div id="nav">
<div><a>Home</a></div>
<div><a>Page2</a></div>
<div><a>Page3</a></div>
<div><a>Page4</a></div>
<div><a>Page5</a></div>
</div>
</div>





All help is appreciated, thank you!

Answer

You can use the table and table-cell method. Basically you need to add the css property display: table to the parent element and display: table-cell; vertical-align: middle to the children ones.

Increased height for demo purpose.

#nav {
  height: 50%;
  background-color: rgb(52, 152, 219);
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  color: white;
  font-family: Calibri;
  font-size: 200%;
  text-align: center;
  display: table;
}
#nav div {
  display: table-cell;
  height: 100%;
  vertical-align: middle;
}
#nav div:hover {
  background-color: rgb(41, 128, 185);
  cursor: pointer;
}
<div id="main">
  <div id="nav">
    <div><a>Home</a>
    </div>
    <div><a>Page2</a>
    </div>
    <div><a>Page3</a>
    </div>
    <div><a>Page4</a>
    </div>
    <div><a>Page5</a>
    </div>
  </div>
</div>

Comments