Kirzilla
Kirzilla

Reputation: 16596

How to clear:both; correctly?

<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">
   <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?

Upvotes: 5

Views: 434

Answers (4)

thirtydot
thirtydot

Reputation: 228182

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/

Upvotes: 5

Michael
Michael

Reputation: 763

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

Upvotes: 1

Eonasdan
Eonasdan

Reputation: 7765

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>

Upvotes: 1

brenjt
brenjt

Reputation: 16297

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

Upvotes: 0

Related Questions