开发者

How to clear:both; correctly?

开发者 https://www.devze.com 2023-04-03 19:24 出处:网络
<style> .cl {clear:both;} .block {} .left {float:left;} </style> <div class=\"block\"> <div class=\"left\">Title 1</div>
<style>
.cl {clear:both;}
.block {}
.left {float:left;}
</style>

<div class="block">
   <div class="left">Title 1</div>
   <div class="left">Value 1</div>
   <div class="cl"></div>
</div>
<div class="block">开发者_StackOverflow社区
   <div class="left">Title 2</div>
   <div class="left">Value 2</div>
   <div class="cl"></div>
</div>

Is it possible to avoid adding <div class="cl"></div> at the end of each .block?


There are two common solutions to this problem.

  1. Add overflow: hidden to the parent of the floated elements (so in this case, .block).
  2. Use "clearfix": http://nicolasgallagher.com/micro-clearfix-hack/

Some more information here: Is clearfix deprecated?


A good time to use clear: both is when you already have an element available to add it to.

For instance, the common case of floated columns with a footer: http://jsfiddle.net/thirtydot/vhBkM/


you could do this:

<style>
    br {clear:both;}
</style>
<div class="block">
    <div class="left">Title 2</div>
    <div class="left">Value 2</div>
</div>
<br/>

a second option re: @animuson comment

<style>
    .container br {clear:both;}
</style>
<div class="container">
   <div class="block">
       <div class="left">Title 2</div>
       <div class="left">Value 2</div>
   </div>
   <br/>
</div>


You shouldn't need the <div class="cl"></div> divs at all. Just put the clear: both on the block div.

Example: http://jsfiddle.net/mKazr/

CSS

.block {
    clear: both;
    overflow: hidden; /* If you want to make the div size to the contents and not collapse use this line (from thirtydot answer) */
} 
.left { float:left; }

HTML

<div class="block">
   <div class="left">Title 1</div>
   <div class="left">Value 1</div>
</div>
<div class="block">
   <div class="left">Title 2</div>
   <div class="left">Value 2</div>
</div>

Edit: added code


Try using overflow:hidden on the .block I know that that sometimes will fix it.

0

精彩评论

暂无评论...
验证码 换一张
取 消