My goal is to perfectly center the text within the anchors in my li
container, both horizontally and vertically. I've come across a method that involves using text-align: center;
on the container for horizontal alignment. However, vertical alignment requires setting the display property of li
to table and a
to table cell.
Not satisfied with this approach, I decided to place the anchor text inside a div
element and attempted to center it using margin: auto;
. Strangely, this only worked horizontally despite the fact that the div
has a specified height as a block element. Can anyone shed light on why this might be?
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>