Web Design & Development

[ Web Design & Development Topics ]

CSS and Layout: Float

We talked briefly about positioning with CSS using either absolute or relative positioning of divs. There is one more item that may be useful to know about in regard to relative positioning, and that is 'float'.

Float

Since divisions are block-level (i.e., they default to 100% of the available screen width and add line breaks between each other), they will all just stack up underneath one another unless you position them in some way. The simplest way to do this is to use the CSS float property, the backbone of most CSS layouts. You can float any element left or right, and it will align itself over to the side of whatever element it is contained within.1

Let's try it.

If I wrote:

<div style="position:relative; float: right; width: 200px; padding: 10px; background-color:yellow; border: thin solid black;">I am the first div</div>
<div style="position:relative; float: right; width: 200px; padding: 10px; background-color:green; border: thin solid black;">I am the second div</div>

I would end up with:

I am the first div
I am the second div

 

If I wrote:

<div style="position:relative; float: left; width: 200px; padding: 10px; background-color:yellow; border: thin solid black;">I am the first div</div>
<div style="position:relative; float: left; width: 200px; padding: 10px; background-color:green; border: thin solid black;">I am the second div</div>

I would end up with:

I am the first div
I am the second div


Learn more about using CSS for layout (including the use of float)