0

I have a navbar with css but the li elements have 2px margin to left and right, even when I use margin: 0, and I have to use margin: 0px -2px to "fix" it

Here is the original code snippet

ul,
li {
    margin:0;
    padding:0;
}
nav{
    background:#333;
}
nav ul{
    text-align: center;
}
nav ul li{
    display:inline-block;
    list-style:none;
}
nav ul li a{
  background: green;
    color:#fff;
    padding:15px;
    display:block;
    text-decoration:none;
    font-weight:600;
    font-size:16px;
}
<nav>
    <ul>
        <li><a href="#">home</a></li>
        <li><a href="#">home2</a></li>
        <li><a href="#">home3</a></li>
        <li><a href="#">home4</a></li>
    </ul>
</nav>
dippas
  • 58,591
  • 15
  • 114
  • 126
Linh Dinh
  • 3
  • 2
  • Try floating your li elements to the left. The display inline-block property doesn't rest the elements directly next to each other. – bullzito Jun 19 '16 at 01:42

1 Answers1

1

when using display: inline-block the element creates a space because it gets inline, so you need to fix that space,

There are few ways to fix that space:

  • Remove the spaces
  • Remove the spaces using html comments <!-- -->
  • Negative margin (personally I don't advise it to use)
  • Skip the closing tag, which HTML5 allows (again personally I don't advise it to use)
  • Set the font-size to zero
  • Set them float
  • Use flexbox

For this code, you can use font-size:0 in parent ul because you are setting already font-size in child a

ul,
li {
  margin: 0;
  padding: 0;
}
nav {
  background: #333;
}
nav ul {
  text-align: center;
  font-size:0
}
nav ul li {
  display: inline-block;
  list-style: none;
}
nav ul li a {
  background: green;
  color: #fff;
  padding: 15px;
  display: block;
  text-decoration: none;
  font-weight: 600;
  font-size: 16px;
}
<nav>
  <ul>
    <li><a href="#">home</a>
    </li>
    <li><a href="#">home2</a>
    </li>
    <li><a href="#">home3</a>
    </li>
    <li><a href="#">home4</a>
    </li>
  </ul>
</nav>
dippas
  • 58,591
  • 15
  • 114
  • 126
  • `display:inline-block` does not create a gap by itself, it rather forces elements to be placed inline and so spaces separating such elements become significant. – c-smile Jun 19 '16 at 01:47
  • @c-smile exactly, I'm aware of that, I know that is the element who gets inline and then inline level elements have those spaces – dippas Jun 19 '16 at 01:55
  • @c-smile I updated the explanation to be more truthfully. Thanks for the heads up. – dippas Jun 19 '16 at 01:59