CSS tip: Float an image without text wrapping under it.

December 10th 2009

I thought I’d share this little CSS tip that can be useful to some of you.

Let’s say you have this content that contains a thumbnail, you want to float the thumbnail but don’t want the text to wrap under it like below.

thumb_bad

Instead you want the thumbnail to float and the text beside it, in it’s own column, like below.

thumb_good

Well that’s fairly easy to do, your markup should look something like this:

<div class="content">
    <img src="thumbnail.jpg" width="50" height="50" alt="Thumb!" />
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis ligula arcu, luctus nec elementum quis, condimentum a lectus. Suspendisse potenti. Proin neque diam, dictum ac elementum scelerisque, aliquet eget diam....</p>
</div>

Now what you actually do, is that instead of floating the thumbnail, you “position:absolute” it inside the content and add padding to the content so the text displays beside the thumbnail.

You CSS should look something like that:

.content {
	padding: 0 0 0 75px; /* 75px being the width of the thumbnail + how much space you want to put between it and your text */
	position: relative; /* So the thumbnail is relative to this */
}

	.content img {
		left: 0;
		position: absolute;
		top: 0;
	}

This should produce the result below. What actually happen is that the thumbnail which is absolutely positioned don’t take the padding of it’s container into account. That’s why it can be positioned over the padding.
thumb_padding

Working demo

Check out my working demo to see it in a real world example.

Bottom line

So by using this technique you’re always sure your text will never wrap under your thumbnail, that’s one less thing to worry about!

Leave a Reply