Neverland Neverland - 15 days ago 4
CSS Question

vertical centering Side Navbar

guys.
I'm pretty new to CSS and it's my first try to create a vertical navbar.
After learning that i need to use -40 margin for my

<li>
to center the text horizontal, i got the next challenge.
I don't get it to center the text vertical.
Maybe someone could help me :-)



body {
font-family: Lato;
}

.nav {
width: 300px;
height: 100%;
margin: -8px;
background-color: grey;
}

.nav li {
list-style: none;
text-align: center;
margin: 0 0 0 -40;
}

.nav li a {
text-decoration: none;
color: black;
font-weight: bold;

}

.nav li a:hover {
color: white;
}

<html>

<head>
<meta charset="utf-8">
<link href="style.css" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
<title>Webdesign</title>
</head>

<body>
<ul class="nav">
<li><a href="#">START</a></li>
<li><a href="#">HOME</a></li>
<li><a href="#">CONTACT</a></li>
</ul>
</body>


</html>




Answer

Few things :

.nav li {
list-style: none;
text-align: center;
margin: 0 0 0 -40; // You forgot to define a unit, so it won't work. (40 what ? px, em, rem, %...)
}

I suggest you to reset margin and padding * {margin:0; padding:0;}, because you added a margin to your li to couterbalance the padding of th ul.

.nav {height:100%;} won't work if all parents (html, body, etc...) don't have a proper height defined.

You can achieve a vertical align in different way, one would be :

*{padding:0; margin:0;}
html, body {height:100%;}
body {
  font-family: Lato;
    vertical-align:middle;
}
div {
  display:table;
  height:100%;
}
.nav {
  width: 300px;
  height: 100%;
  background-color: grey;
  display:table-cell;
  vertical-align:middle;
}

.nav li {
  list-style: none;
  text-align: center;
}

.nav li a {
  text-decoration: none;
  color: black;
  font-weight: bold;
  
}

.nav li a:hover {
  color: white;
}
<body>
  <div>
    <ul class="nav">
      <li><a href="#">START</a></li>
      <li><a href="#">HOME</a></li>
      <li><a href="#">CONTACT</a></li>
    </ul>
  </div>
</body>

What I did is:

  • Added a div wrapping the ul
  • Added a height:100%; to html, body and that div
  • Added display:table; to that div
  • Added display:table-cell; vertical-align:middle; to your .nav