Wednesday, May 19, 2010

CSS Clear Property

The clear property is as important when building a website based on float. The float property could be described as ignoring the line breaks, this does not only mean that the floating elements may be placed beside each other, but also that the web browser can't know where your elements end if you don't set a specific height; which is seldom an optimal solution. So how do we solve this?

The clear property

The clear property could be described as telling the web browser where your floating elements end by "clearing the row". For example, if you put two images inside a layer without specifying the layer height; the layer would normally adjust to the images, but not if the images are floating.

Code below.

CSS

.first_div { background-color: #8BC792; padding: 20px; }
.float_left { float: left; }

XHTML

<div class='first_div'>
<img class='float_left' src='flower.jpg' alt='' />
<img class='float_left' src='icetap.jpg' alt='' />
</div>

Demo: Div containing two floating images.

As you can see the layer don't recognizes the images height because they are floating. The only visible part of the layer is caused by padding specified in the CSS class applied to the layer.

How are we going to fix this problem? As you might have guessed; we will apply the float property by adding a div with the CSS property applied to it beneath the images. As you can float elements to the left or to the right, you can also clear the row to the left or to the right but you are also able to clear both. I prefer to always use both to avoid confusion.

<div style='clear: both;'> </div< /* left, right or both */

With this placed in the right place; the browser will recognize the height of the floating elements, in this case two images.

example code below.

CSS

.first_div { background-color: #8BC792; padding: 20px; }

.float_left { float: left; }

.clear { clear: both; }

XHTML

<div class='first_div'>
<img class='float_left' src='flower.jpg' alt='' />
<img class='float_left' src='icetap.jpg' alt='' />
<div class='clear'></div> /* A div with the CSS class applied to it */
</div>

Demo: Div containing two floating images with "clear".

As you can see the layer now recognize the height of the images which makes you able to place other elements beneath it.

Another use for float on images is also to replace the html align='left/right' attribute which isn't valid in either XHTML 1.0 Strict or XHTML 1.1. Simple float the image instead of aligning it.

Source from : dashdev