ShadowDragon ShadowDragon - 3 months ago 10
CSS Question

HTML & CSS Center navigation bar

I've got the problem that on my small test website I can't get the navigation bar centered.
I want to have all the buttons on it centered while the navigation bar goes from the right to the left side of the website. I've got no fixed width and don't want to have one. The solution should also work with smartphones and tablets and just to mention: I don't really care about IE support.
I already searched a bit through the web but got nothing I've tried working.

Here is the code I've already got:

<header class="navigation">
<nav>
<ul>
<li><a class="active" href="#home">Home</a></li>
<li><a href="#download">Download</a></li>
<li><a href="#contact">Contact</a></li>
<!-- Maybe the navigation bar gets more buttons in the future. -->
</ul>
</nav>

<h1>Test Test Test</h1>
</header>


And here is the CSS code:

ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
border-radius: 5px;
background-color: #333333;
}

li { float: left; }

li a {
display: block;
color: white;
text-align: center;
padding: 16px;
text-decoration: none;
border-bottom: none;
}

li a:hover { background-color: #111111 }


I'm using HTML5 with CSS3.

EDIT: It seems to be that I wasn't clear enough with the buttons. The buttons should not be as large as the navigation bar itself. All buttons should be centered on the navigation bar, so in the middle there are the buttons and on the left and right side there is just the black navigation bar without buttons if there is enough space left, ofcourse.

Answer

Using flexbox will do exactly that...

adding flex-flow: row wrap; will allow the menu to wrap on smaller screens if the navigation is larger than the viewport.

You will need to prefix those styles to run on all browsers FYI.

.navigation nav {
  display: flex;
  justify-content: center;
  
  background-color: #333333;
}
ul {
  display: flex;
  flex-flow: row wrap;
  
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  border-radius: 5px;
}
li a {
  display: block;
  color: white;
  text-align: center;
  padding: 16px;
  text-decoration: none;
  border-bottom: none;
}
li a:hover {
  background-color: #111111
}
<header class="navigation">
  <nav>
    <ul>
      <li><a class="active" href="#home">Home</a>
      </li>
      <li><a href="#download">Download</a>
      </li>
      <li><a href="#contact">Contact</a>
      </li>
      <!-- Maybe the navigation bar gets more buttons in the future. -->
    </ul>
  </nav>

  <h1>Test Test Test</h1>
</header>