-1

I've been fiddling around with nav bars and I just cannot figure out how to centre them. I am currently using this one from w3schools.com.

I would like the clickable boxes (Home, News, Contact, About me) to be in the centre of the page and not on the left. How do I do this?

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
}
li {
  float: left;
}
li a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}
li a:hover:not(.active) {
  background-color: #111;
}
.active {
  background-color: #4CAF50;
}
<ul>
  <li>
    <a class="active" href="#home">Home</a>
  </li>
  <li>
    <a href="#news">News</a>
  </li>
  <li>
    <a href="#contact">Contact</a>
  </li>
  <li>
    <a href="#about">About</a>
  </li>
</ul>
jaunt
  • 4,978
  • 4
  • 33
  • 54
Forrest
  • 567
  • 1
  • 5
  • 10

3 Answers3

1

add

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
  padding-left:30em;
}

though i recommend using bootstrap. It makes work lot easier.

  • Thank you this worked! I wanna try and get into using bootstrap a some point. Just thought I'd learn some basics first. Thanks! – Forrest Feb 13 '16 at 14:54
  • why is there a `padding-left:30em;` ? – Lal Feb 13 '16 at 14:58
  • How does the above CSS make it centered? see the [fiddle](https://jsfiddle.net/lalu050/mbz067sv/1/) with the above CSS. – Lal Feb 13 '16 at 15:02
0

See this fiddle

To make the <li>s centered, you will have to remove the float:left property that is set for the <li>s . Instead you have to use display:inline-block. And now, to make the <li>s centered, add text-align:center for the <ul>

Change your CSS as follows

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
  text-align:center;
}
li {
  /* float: left; */
    display: inline-block;
}
Lal
  • 14,726
  • 4
  • 45
  • 70
0

The answer to this is to perhaps not use lists for making the nav bar, try this code instead, it's pretty simple to understand:

<style>
#test {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  background-color: #333;
  text-align: center;
  padding-top: 10px;
  padding-bottom: 13px;
}

a {
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

a:hover:not(.active) {
  background-color: #111;
}

.active {
  background-color: #4CAF50;
}

</style>

<body>

<div id='test'>
  <a class="active" href="#home">Home</a>
  <a href="#news">News</a>
  <a href="#contact">Contact</a>
  <a href="#about">About</a>
</div>