Login | Contact Us | Site Map | Resources

The Inner Workings of CSS

Home > CSS Tutorial > CSS Floating

CSS Floating

Using CSS, an HTML element can be pushed, or "floated", to the far left or the far right of its containing element, allowing text and other inline elements to wrap around it. This is a feature most commonly used on images, although some layouts use it as well.

<p style="border: 1px solid #0096C5;">
  <img src="elephant.gif" style="float: right;" />
  Paragraph Text Goes Here
</p>

This example, with "float: right;" in the <img /> element, will result in the following paragraph:

A doctor of psychology was doing his normal morning rounds when he entered a patient's room. He found Patient #1 sitting on the floor, pretending to saw a piece of wood in half.

Patient #2 was hanging from the ceiling, by his feet.

The doctor asked Patient #1 what he was doing. The patient replied, "I'm sawing this piece of wood in half." The doctor inquired of Patient #1 what Patient #2 was doing. Patient #1 replied, "Oh. He thinks he's a light bulb."

The doctor looks up and notices Patient #2's face is going all red, so he asks Patient #1, "Shouldn't we ask him to get down from there before he hurts himself?"

Patient #1 replies, "What? And work in the dark?"

(It will sometimes be necessary to set a margin around the floated element so that the surrounding text does not run into it.)

If multiple elements are floated to the same side they will be lined up next to each other, but if the "clear" attribute is set in each element with a value of "left" or "right" (depending on the side the elements are floated to), each new element will float to that side below the previous element instead of beside it.

<p style="border: 1px solid #0096C5;">
  <img src="elephant.gif" style="float: left; clear: left;" />
  <img src="fish-orange.gif" style="float: left; clear: left;" />
  Paragraph Text Goes Here
</p>

The above example will result in the following paragraph:

While sports fishing off the Florida coast, a tourist capsized his boat. He could swim, but his fear of alligators kept him clinging to the overturned craft.

Spotting an old beachcomber standing on the shore, the tourist shouted, "Are there any gators around here?!"

"Naw," the man hollered back, "they ain't been around for years!"

"Feeling safe, the tourist started swimming leisurely toward the shore.

About halfway there he asked the guy, "How'd you get rid of the gators?"

"We didn't do nothin'," the beachcomber said.

"The sharks got 'em."