Centering <li> elements within a div element

Does anybody know how i could center my <li> elements within my <div> element that has been centered using margin: auto? i am trying to create a nav bar. i’ve centered the bar, but my <li> elements are positioned using position:absolute(left input, top input) so they’re not truly centered. Only centered on my screen.


<div id="navbar"></div>  
  <li style="position:absolute; left: 590px; top: -35px"><a href="#about">About</a></li>   
  <li style="position:absolute; left: 674px; top: -35px" id="navbutton"><a href="#portfolio">Portfolio</a></li>
  <li style="position:absolute; left: 795px; top: -35px" id="navbutton"><a href="#contact">Contact</a></li>


body {
    background-image: url("");
  background-repeat: no-repeat;
  background-size: cover;
ul {
  list-style-type: none;
  margin: 0; padidng:0; position:fixed;

a { 
  border-radius: 10px;   
  width: 120px; 
  background-color: rgb(80, 150, 600);
  color: white;
  text-decoration: none;
  text-transform: uppercase;  
  text-align: center; padding: 10px;

li {display: inline; }

#navbar {
  width: 350px;
  height: 50px;
  opacity: .5;
  background-color: rgb(0, 120, 120);
  margin: auto;

CSS Flexbox makes things like this quite simple.

Simply modify your container element, in this case ul to display: flex. This will set your list up as a flex container, and from there you can modify the li elements within it as flex items. To center all the lists’ items horizontally, you would need to add the justify-content: center property to the ul container element.

You can remove the position: absolute property on the li elements, flex items will only take up as much space as they need. Unless you want all the li elements to be spaced evenly apart along the navbar, for that you can use justify-content: space-around

1 Like

I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.

You code was formatted really badly, and I had problems seeing what you had. If the redone code is not correct, please fix it.

1 Like