Positioning in CSS with clear

Once you have set up a float you may need certain elements to not wrap. Clear allows this.

Imagine you want images with captions to float across the page. Here it is without clear:

This paragaph is above the images.

Fred

Fred

Freda

Freda

Freddie

Freddie

Frederica

Frederica

This one is below the images (or not).

You really wanted that last paragraph to be clear of the images but it floated alongside it.

Here are the CSS and HTML to add to the styles and BODY of a Web page:

#imagecontainer {
			
}
        
div.floatedimage {
	background-color:yellow;							
	height:8em;
	width:6em;
	padding:0px;
	margin:0px;
	border-width:1px;
	border-style:solid;
	border-color:black;
	float:left;
}
        
<div id="imagecontainer">
	<div class="floatedimage">
		<img src="./files/examples/fred.jpg" alt="Fred" />
		<p>Fred</p>
	</div>
	<div class="floatedimage">
		<img src="./files/examples/freda.jpg" alt="Freda" />
		<p>Freda</p>
	</div>
	<div class="floatedimage">
		<img src="./files/examples/freddie.jpg" alt="Freddie" />
		<p>Freddie</p>
	</div>
	<div class="floatedimage">
		<img src="./files/examples/frederica.jpg" alt="Frederica" />
		<p>Frederica</p>
	</div>	
</div>
<p>This one is below the menu</p>
        

Try those and then put this in the #imagecontainer styles section above:

clear:both;    
        

In some older browsers the paragraph will probably be cleared and will appear below the menu but any browser which follows the rules will leave the text apparently floated. You might think this is a problem but it is correct behaviour. Try adding a background-color to the container DIV.

If you ever have trouble with clear in some browsers remember that a DIV does not necessarily grow to fit the content in it. If text seems to wrap alongside the content then it may be that your containing DIV is the wrong size (zero height). That is the problem with the above code. Add a height declaration to the CSS for #imagecontainer and try it again:

height:8em;    
        

You should find that the second paragraph now clears the menu entries in all browsers because the DIV height matches the content height.

Alternatives for clear:both include clear:left and clear:right.

submit to reddit Delicious Tweet