0

Here is the following HTML/CSS.

li {
  float: left;
  background-color: #BD4932;
}

li a {
  display: block;
  padding: .5em 1em;
  color: #FFFAD5;
}
<h1>Dynamic horizontal centering</h1>
<h2>With <span class="orange">display:table</span></h2>
<nav role='navigation' class="nav-table">
  <ul>
    <li><a href="#">Home</a></li>
    <li><a href="#">About</a></li>
    <li><a href="#">Clients</a></li>
    <li><a href="#">Contact Us</a></li>
  </ul>
</nav>

Results: http://codepen.io/anon/pen/LVeBGv

My understanding is that block level elements force following elements to a new line. Why doesn't the display: block; put the list items in new line?

JJJ
  • 32,902
  • 20
  • 89
  • 102
mikelee54
  • 29
  • 9
  • 3
    It's because of the _float: left;_. For some more info read [this stackoverflow](http://stackoverflow.com/questions/15172520/advantages-of-using-displayinline-block-vs-floatleft-in-css). – Robin Jun 29 '15 at 14:29

3 Answers3

3

No, block level elements by default take 100% width of their parent. The won't push the next element in a new line. Your anchors parent (the list-item) is floated to the left, meaning that it will only be as width as it's content.

If you want the anchors (and list-items) to move to the next line, then remove the float: left from the li

li {
  /*float: left;*/
  background-color: #BD4932;
}

li a {
  display: block;
  padding: .5em 1em;
  color: #FFFAD5;
}
<h1>Dynamic horizontal centering</h1>
<h2>With <span class="orange">display:table</span></h2>
<nav role='navigation' class="nav-table">
  <ul>
    <li><a href="#">Home</a></li>
    <li><a href="#">About</a></li>
    <li><a href="#">Clients</a></li>
    <li><a href="#">Contact Us</a></li>
  </ul>
</nav>

or add clear: both to it:

li {
  float: left;
  clear: both;
  background-color: #BD4932;
}

li a {
  display: block;
  padding: .5em 1em;
  color: #FFFAD5;
}
<h1>Dynamic horizontal centering</h1>
<h2>With <span class="orange">display:table</span></h2>
<nav role='navigation' class="nav-table">
  <ul>
    <li><a href="#">Home</a></li>
    <li><a href="#">About</a></li>
    <li><a href="#">Clients</a></li>
    <li><a href="#">Contact Us</a></li>
  </ul>
</nav>
GreyRoofPigeon
  • 17,833
  • 4
  • 36
  • 59
1

Because you are using float: left.

display: block is redundant if you've specified float: left (or right).

Alex Char
  • 32,879
  • 9
  • 49
  • 70
0

This will do what you asked for. (Take off the float:left;)

ul {
     list-style: none;    
   }

li {
      background-color: #BD4932;
    }

    li a {
      display: block;
      padding: .5em 1em;
      color: #FFFAD5;
    }

    <h1>Dynamic horizontal centering</h1>
    <h2>With <span class="orange">display:table</span></h2>
    <nav role='navigation' class="nav-table">
      <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">About</a></li>
        <li><a href="#">Clients</a></li>
        <li><a href="#">Contact Us</a></li>
      </ul>
    </nav>