Where should I put the "clear: both"?

时间:2016-07-11 20:49:05

标签: css css-float

I'm struggling to understand which should be the correct position of the clear:both; in the code.

<div class="first-row">
   <div class="left-column" style="float:left;width:33%;"></div>
   <div class="center-column" style="float:left;width:33%;"></div>
   <div class="right-column" style="float:left;width:33%;"></div>
   <div style="clear:both;"></div> <!-- first option -->
</div>
<div style="clear:both;"></div> <!-- second option -->
<div class="second-row">
    etc....
</div>

1 个答案:

答案 0 :(得分:2)

The "first option" in your example is recommended. If you set the borders for background e.g. .first-row{border:1px solid red;} you will be able to see it clearly that it prevents the container to collapse.

In the "second option", it only clears the float that is above itself, so that "second-row" will start on a new line.

In fact, using the pseudo element :after is most popular clearfix method nowadays. As you can see it's placed right before closing tag of the container, same idea as "first option".

.first-row:after {
  content: "";
  clear: both;
  display: table;
}