float: left;

margin: 0px 20px 10px 0px;

5.23 image

Some points to note

Floats will always honour the padding of their parent container. When we float an element, the element will float within the constraints of its parent element (container). This means that if the container has a padding of say 20px, then our left floated image will sit in the far left left-hand corner of this element offset by 20px as we can see in Figure 5.24.

5.24 image

Floating inline elements

The float property is extremely powerful. We can even specify floats on inline elements, such as the <p> tag. Floating an inline element will force it to behave just like a block element, meaning that it will be wrapped up tightly and put into the next available space.

Sizing

When floating an element, generally you will want to specify a width for the element. By default the element will expand as far as the content inside it needs to, so if the content is text based, it will expand to the entire width of the containing element. Specifying a width of say 200px, will force the height to expand and will restrict the width of the element to allow us to move it into place, which is the main purpose of floating an element.

Clearing floats

We can use the ‘clear’ property to force an element to ignore the floats used above it. For example, if I float an image in the top left of a container, then add another element in the HTML, by default the next element will flow around the floated image. This isn’t always the desired outcome, however. This is where the clear property comes into play. We can declare the clear property with any of the following values: left, right, both, none.

Let’s consider the following example where we have a left and right floated image. You will notice that the right image is slightly longer than the left image, and that the inline paragraph element is flowing nicely around the images.

5.25 image

Let’s look at how this example changes when we make use of the clear property on our paragraph tag.

Specifying ‘left’ will force the new element to break out on to the next available space underneath the bottom of the lowest reaching left floated element above.