mikelee54
mikelee54

Reputation: 29

Block level elements behavior

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?

Upvotes: 0

Views: 62

Answers (3)

Alaoui Zoubair
Alaoui Zoubair

Reputation: 81

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>

Upvotes: 0

GreyRoofPigeon
GreyRoofPigeon

Reputation: 18123

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>

Upvotes: 3

Alex Char
Alex Char

Reputation: 33218

Because you are using float: left.

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

Upvotes: 1

Related Questions