CSS Text Flow Around Image

Perm url with updates: http://xahlee.org/js/css_flow_over_image.html

(css effect may not show in blogger. Visit the link above to see full effect.)

CSS Text Flow Around Image

Xah Lee, 2010-03-20

This page shows you how to use CSS so that text wraps around image.

lilies-s The Time Traveller (for so it will be convenient to speak of him) was expounding a recondite matter to us. His grey eyes shone and twinkled, and his usually pale face was flushed and animated. The fire burned brightly, and the soft radiance of the incandescent lights in the lilies of silver caught the bubbles that flashed and passed in our glasses. Our chairs, being his patents, embraced and caressed us rather than submitted to be sat upon, and there was that luxurious after-dinner atmosphere when thought runs gracefully free of the trammels of precision. And he put it to us in this way—marking the points with a lean forefinger—as we sat and lazily admired his earnestness over this new paradox (as we thought it) and his fecundity.

The above is the opening paragraph of Time Machine by H G Wells. You can see the text flowing around a image. This is done using css with “float”.

Solution

The html is like this:

<p><img class="floatMe" src="lilies.png" alt="lilies" width="167" height="106">
The Time Traveller...</p>

The css is even simpler, like this:

img.floatMe {float:left; margin:1ex}

The “float” can have a value of “left” or “right”, meaning that it aligns to the left of the bounding box or to the right. If any ancestor tag doesn't have any width set, then the bounding box is the window.

When a tag is floating, anything will go around it to avoid collision or overlap. (except tags that have their own layer with “position”. See: CSS Layout and Layers)

You can have multiple tags that are all floating. If they all have “float:right”, then they'll behave as a sequence of “<img ...>” tags, flowing from left to right. For a example, see: Flowing List Items.

Stop Flowing

If you have many floating items, the position of the last item will be the positon the next non-floating item begin. For example, you might have:

FBox FBox FBox FBox FBox <h2>

where each FBox is a tag with “float:left”. The “<h2>” will be shown at the position right after the the last floaw. You don't want that. In that situation, you need to give a “clear:left” in the tag that comes after the float. Like this:

<h2 style="clear:both">A New Beginning</h2>

The “clear” can have values of “left”, “right”, “both”.

Usually, it is best to use this tag to clear the floats:

<hr style="display:none; clear:both">

Popular posts from this blog

11 Years of Writing About Emacs

does md5 creates more randomness?

Google Code shutting down, future of ErgoEmacs