-1

I have a ul that I am using for my page navigation and I would like to center it but I can't figure out how to do it. Here is my code:

<ul id="nav">
<li><a href="#">Home</a></li>
<li><a href="#">What Are Drones</a></li>
<li><a href="#">How Do Drones Work</a></li>
<li><a href="#">Buying a Drone</a></li>
 <li><a href="#">About Us</a></li>
</ul>


#nav { list-style-type: none; height: 100px; padding: 0; margin: 0; }
#nav { list-style-type: none; height: 100px; padding: 0; margin: 0; }
#nav li { display:inline-block; position: relative; padding: 0; line-height:    100px; background: #666 url(nav-bg.png) repeat-x 0 0; }
#nav li:hover { background-position: 0 -40px; }
#nav li a { display: block; padding: 0 15px; color: #fff; text-decoration: none; font-size: 50px; font-family: 'Cuprum', sans-serif; }
#nav li a:hover { color:#0F0 }
#nav li ul { opacity: 0; position: absolute; left: 0; width: 8em; background: #63867f; list-style-type: none; padding: 0; margin: 0; }
#nav li:hover ul { opacity: 1; }
#nav li ul li { float: none; position: static; height: 0; line-height: 0; background: none; }
#nav li:hover ul li { height: 30px; line-height: 30px; }
#nav li ul li a { background:#666 }
#nav li ul li a:hover { background:#666 }
#nav { background-color:#666; }
  • 1
    have you searched around stackoverflow looking for it? theres thousands of questions like this; – L777 Mar 17 '16 at 20:49
  • 1
    Possible duplicate of [CSS center ul list](http://stackoverflow.com/questions/21172989/css-center-ul-list) – Roy Mar 17 '16 at 20:51
  • Possible duplicate of [How to horizontally center an unordered list of unknown width?](http://stackoverflow.com/questions/1695175/how-to-horizontally-center-an-unordered-list-of-unknown-width) – TylerH Mar 18 '16 at 12:39

2 Answers2

0

Here is the simplest solution to center a list:

#nav {
  display: table;
  margin: auto;
}
#nav > li {
  display: block;
}
<ul id="nav">
  <li><a href="#">Home</a></li>
  <li><a href="#">What Are Drones</a></li>
  <li><a href="#">How Do Drones Work</a></li>
  <li><a href="#">Buying a Drone</a></li>
  <li><a href="#">About Us</a></li>
</ul>

I used display: table because:

  1. It fits to its content, like display: inline-block
  2. It allows me to center it without using an extra element.
tzi
  • 8,719
  • 2
  • 25
  • 45
0

It really depends on what you're trying to do, your constraints and how you are trying to build your site but for me setting text-align:center; on your #nav element centers all of the individual menu elements relative to which row they appear on.

You can read more here if you need to get into the finer arts of it: https://css-tricks.com/centering-list-items-horizontally-slightly-trickier-than-you-might-think/

But as they say this is pretty simple in modern HTML. It's only if you need to support older browsers for some reason or some other quirky setup that it gets more complex.

ChrisM
  • 1,565
  • 14
  • 24