In my HTML I have an unordered list of links. In my CSS I am trying to center the list of links horizontally on the webpage. Here is my HTML and CSS code:
@import url("https://fonts.googleapis.com/css2?family=Roboto&display=swap");
* {
margin: 0;
padding: 0;
box-sizing: border-box
}
body {
font-size: 2rem;
font-family: "Roboto", sans-serif;
}
ul {
display: inline-block;
margin: 0px, auto;
list-style: none;
padding: 0.5rem;
background-color: black;
}
li {
display: inline-block;
margin-inline: 0.5rem;
}
li a {
color: white;
text-decoration: none;
}
li a:hover, li a:focus {
text-decoration: underline;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Display</title>
<link rel="stylesheet" href="practice.css">
</head>
<body>
<main>
<nav>
<ul>
<li><a href="#">Intro</a></li>
<li><a href="#">Portfolio</a></li>
<li><a href="#">Projects</a></li>
</ul>
</nav>
</main>
</body>
</html>
I thought setting the unordered list to an inline-block would allow me to apply margins onto the unordered list element. If so, my margins were set to margin: 0px, auto; which should have centered the unordered list horizontally, but for some reason none of the CSS is being applied. I am very much focused on WHY this does not work rather than an alternative solution. Thanks!
4
Answers
Change this line:
To this:
To fix the issue, you can change the comma to a space. This should center your unordered list horizontally on the webpage.
It’s not centered because it flows on the page in the same way inline elements do. You can achieve centering by making the ul element’s position absolute and the usage of the transform property:
Two things you need to do:
1 . Give
display: flex
to yournav
2 . margin is not correctly provided for
ul
, it should be without a commaWorking code below:
Kamil is correct. There is an error in your syntax. Remove the comma from your margin declaration.
To center your list you should remove
display:inline-block;
from your ul and add a width less than 100%. This will allow your list to be centered on the page.Inline-block elements do not have an inherent width. Therefore,
margin:auto;
will not work.