An example of the float quirk

While the float quirk issue is by no means solely confined to images, it is most commonly associated with them, and so is addressed here.

The “float quirk” problem typically occurs when you have images that are both floated on the same side of the page in close proximity to each other. In our example, we will have a class that describes a similar format for a set of images.

For example, a CSS class in an embedded stylesheet, inside the <head> of your HTML page:


<style>img.theremin {
	height: 370px;
	width: 300px;
	float: right;
	margin-left: 1em;
}</style>

And for the markup:

<p><img src="theremin.jpg" class="theremin" alt="Theremin performer">
The theremin is one of the only truly new musical instruments
created in the 20th century.
<p>It remains the only musical instrument that is not
physically touched to produce a tone.
<p><img src="gort.jpg" class="theremin" alt="Gort">
Sounds produced by the theremin are continuous and
glissading, creating an “eerie” or haunting tone.

Float Quirk Solution ScreenshotThe result will typically look something like the screenshot above. As the width of the browser window narrows, the second image will be forced down, until the point at which it “pops” under the first, to produce the effect that we were likely after in the first place.

So what is happening? Very simply, CSS is doing exactly what you tell it. float: right applied to an element means “float to the right of any content that comes after me”. For the first image, that content includes the second image, which follows it.

In order to fix this problem, we need to modify the CSS for the second image. The existing class is still true for both images, so ideally we could add to it:

img.theremin {
	height: 370px;
	width: 300px;
	float: right;
	margin-left: 1em;
	clear: right;
}

(If the images were different sizes and had separate inline styles we would only need to add clear: right; to the the second image. For this example, adding clear to the class is a little redundant, as the first image won't be affected, but it is a more efficient approach than adding a separate inline style to the second image.)

clear is a deceptively simple property that can take one of five values: left, right, both, inherit and none. It essentially means the following: “do not allow anything to float to this side of me”. In our case, our images are floated right; we don’t want anything to be to the right of those images, and clear: right takes care of that.

We would also typically add a margin-bottom property to separate the images visually:

img.theremin {
	height: 370px;
	width: 300px;
	float: right;
	clear: right;
	margin: 0 0 2em 1em;
}

Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.