Katallone
Katallone

Reputation: 335

CSS margin:0 auto not working on li>a

I want a navigation bar with its elements (li>a) to be in the middle. I achieved only the float left style.

#wrapper {
  width: 900px;
  margin: 0 auto;
}
li {
  float: left;
}
ul>li>a {
  display: block;
  padding: 14px 16px;
  color: #fff;
  text-align: center;
  text-decoration: none;
  margin: 0 auto;
  font: 18px Inconsolata;
}
/* fdfdf */

ul {
  list-style: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
  border-radius: 20px;
}
ul>li:hover {
  background: #111;
}
li>a.active {
  background-color: #4CAF50;
  color: #fff;
}
<div id='wrapper'>
  <ul>
    <li><a class='active' href="#">Home</a>
    </li>
    <li><a href="#">Blog</a>
    </li>
  </ul>
</div>

As you see I put in ul>li>a {margin:0 auto;}

Why doesn't it work?

Nav bar: enter image description here

Upvotes: 4

Views: 559

Answers (2)

Unamata Sanatarai
Unamata Sanatarai

Reputation: 6637

https://jsfiddle.net/h933o3jy/

You would need to make the li a inline element, and the parent of it should center it via text-align:center. like so:

#wrapper{
width:900px;
margin:0 auto;
text-align:center;
}

li {
  display:inline-block;
}

udpate

You will notice there's a space between those li items. To get rid of them, construct the HTML in a way that those tags are glued together. For example: https://jsfiddle.net/h933o3jy/1/ </li><li>

Upvotes: 4

Sowmya
Sowmya

Reputation: 26969

margin on a is working but since li has float:left it is behaving as auto width.

If you are sure about having only 2 menu items you can remove the float:left from li and add float to only first li

ul li:first-child{
      float: left;
}

DEMO

Or add width:50% to li

li{
  float:left;
  width:50%
}

Demo 2

Upvotes: 1

Related Questions