Allison Stafford Allison Stafford - 4 months ago 8
CSS Question

Why is there whitespace separating list items from its parentr?

This is my first time implementing the standard html nav. However, the list elements inside nav are not positioned inside nav the way I want them to be, and although I've changed most of the obvious properties that come to mind, I haven't been able to:


  • Center the li elements inside nav

  • Make the width of the li elements fit perfectly inside nav



I don't understand why they are by default positioned so awkwardly to the right of their parent container, or why setting 'width: 100%' isn't the solution. When I set the positioning on the li elements to absolute, it seems to mucks up everything since I need each list element to be positioned relative to where the element before it is placed.

There seems to be a few possible ways I could go about solving this problem, but they seem sort of hackish, and I'm wondering if there's a more obvious solution I lack the experience to see.



nav {
width: 40%; height: 500px;
left: 50%;
transform: translateX(-50%);
position: relative;
border: 2px solid black;
}

nav ul li {
list-style: none; text-align: center;
width: 99%; height: 100%;
position: inherit;
padding: 1%;
border: 2px solid black;
border-top: none;
margin: 0;
display: block;
background: blue;
}

<nav><!--
--><ul><!--
--><li class="user">WelcomeVids</li>
<li class="user">Diablo</li>
<li class="user">FreeCodeCamp</li>
<li class="user">OtherStuff</li>
<li class="user">Dota2</li><!--
--></ul><!--
--></nav>





To see the output, view my Codepen: http://codepen.io/sentedelviento/full/grzrgR/

Answer

This is because most browsers default to adding a padding-left to <ul>. You can override that:

/* Added */
ul {
  padding-left: 0;
}

nav {
  width: 40%; height: 500px;
  left: 50%;
  transform: translateX(-50%);
  position: relative;
  border: 2px solid black; 
}

nav ul li {
  list-style: none; text-align: center;
  /* width: 99%; height: 100%; */
  position: inherit;
  padding: 1%;
  border: 2px solid black;
  border-top: none;
  margin: 0;
  display: block;
  background: blue;
}
<nav><!--
  --><ul><!--
   --><li class="user">WelcomeVids</li>
      <li class="user">Diablo</li>
      <li class="user">FreeCodeCamp</li>
      <li class="user">OtherStuff</li>
      <li class="user">Dota2</li><!--
  --></ul><!--
--></nav>