I want to center the text of my anchors (both horizontally and vertically) within their li
container.
I've read that I can trivially center them orizzontally by using text-align: center;
on the container.
But to center them vertically I would need to display li
as a table and a
as a table cell.
I didn't like this method so I put the text of the anchor into a div
and tried to center the div
with margin: auto;
. For some reason this works only horizontally, even though the div
is a block element with a defined height. Anyone knows the reason why?
html {
box-sizing: border-box;
}
* {
box-sizing: inherit;
margin: 0;
padding: 0;
}
nav ul {
display: flex;
list-style: none;
justify-content: center;
align-items: center;
height: 4em;
background-color: #783F27;
}
nav ul li a {
display: block;
border: solid medium;
border-radius: 0.4em;
margin: 0 0.5em;
width: 7em;
height: 3em;
color: goldenrod;
}
a div {
width: max-content;
height: max-content;
margin: auto;
}
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Learning</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<header>
<nav>
<ul>
<li><a href=""><div>Menu</div></a></li>
<li><a href=""><div>News</div></a></li>
<li><a href=""><div>About</div></a>
<li><a href=""><div>Contact</div></a></li>
</ul>
</nav>
</header>
</body>
</html>