A191919 A191919 - 6 months ago 27
HTML Question

Css align tag a inside li, vertical menu

How to make vertical and horizontal align

middle
of tag
a
inside
li
? Why
vertical-align:middle;
inside
ul
li
does not work? What is better to use
padding
or
vertical-align
?



body{
margin:0;
}
.col1{
width:150px;
border:solid;
height:750px;
display:table;
}
ul{
margin:0;
padding:0;
}
ul li{
list-style:none;
height:40px;
vertical-align:middle;
}
ul li a{
text-decoration:none;
}

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="col1">
<ul>
<li><a href="">Items</a></li>
<li><a href="">Products</a></li>
<li><a href="">Contacts</a></li>
<li><a href="">Other</a></li>
<li><a href="">Email</a></li>
</ul>
</div>
</body>
</html>




Answer

Add the following to your <ul>. The reason it will work is because the parent of <ul> has its display set to display: table; Children will respond to vertical: align center; if their display value is set to table-cell. Also notice that we're positioning the <ul> itself and not the individual <li>s.

ul {
  ...
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}

Also, consider setting .col1's height to 100vh instead of a hard-coded pixel value.

.col1 {
  ...
  height: 100vh;
}

To vertically align the anchor inside of each individual list item, we add the following:

ul li {
  ...
  position: relative;
}
ul li a {
  ...
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

Output

enter image description here

http://codepen.io/antibland/pen/jqdwqG

Comments