Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Practice for CSS Clear or Overflow [closed]

Tags:

css

css-float

Having a discussion with a co-worker on what is best practice with CSS clear / overflow. Please shut one of us up and explain why one is better than the other.

JOEL'S CODE (using overflow):

<style>
  .container { overflow: hidden; }
  .one, .two { float: left; width: 50px; height: 50px; background-color: red; }
</style>

<div class="container">
   <div class="one"></div>
   <div class="two"></div>
</div>
<div class="container">
   <div class="one"></div>
   <div class="two"></div>
</div>
<div class="container">
   <div class="one"></div>
   <div class="two"></div>
</div>
<div class="container">
   <div class="one"></div>
   <div class="two"></div>
</div>

CHRIS' CODE (using clear):

<style>
  .clear { clear: both; }
  .one, .two { float: left; width: 50px; height: 50px; background-color: red; }
</style>

<div class="container">
   <div class="one"></div>
   <div class="two"></div>
   <div class="clear"></div>
</div>
<div class="container">
   <div class="one"></div>
   <div class="two"></div>
   <div class="clear"></div>
</div>
<div class="container">
   <div class="one"></div>
   <div class="two"></div>
   <div class="clear"></div>
</div>
<div class="container">
   <div class="one"></div>
   <div class="two"></div>
   <div class="clear"></div>
</div>

Both make this image:

Properly positioned elements

Who is right? :)

like image 221
Joel Avatar asked Dec 19 '11 16:12

Joel


2 Answers

If you are in a situation where you always know what the succeeding element is going to be, you can apply the clear: both; value to that element and go about your business. This is ideal as it requires no fancy hacks and no additional elements making it perfectly semantic. Of course things don't typically work out that way and we need to have more float-clearing tools in our toolbox.

http://css-tricks.com/all-about-floats/

like image 66
Phil Klein Avatar answered Sep 24 '22 01:09

Phil Klein


overflow:hidden is best used when you have a container which is smaller than the content inside; whereas clear:both is best used when you want a floating container to NOT position itself alongside the nearest container.

looking at your red squres example, you would want to use clear rather than overflow, but not as its done here. perhaps something more like:

.container { width:110px; clear:both; }
.one, .two { float: left; width: 50px; height: 50px; margin-right:10px; background-color: red; }

basically you are both wrong and right. Joel uses the better html approach, but Chris is using the right bit of CSS code, just in the wrong way.

like image 43
Jimmery Avatar answered Sep 23 '22 01:09

Jimmery