Linh Dinh Linh Dinh - 5 months ago 24
CSS Question

Unknown margin of li elements

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>




Answer

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>

Comments