Friday, 27 May 2011

CSS: float!


The float property is not really new. It has been used a lot, especially in blogs and online magazine. The most common use is when we need to put an image in a container and make the text surround it. Like this:

Lorem ipsum dolor sit amet, imperdiet in massa risus ultricies, nulla neque commodo quisque, varius vitae odio, urna mi massa semper pellentesque faucibus turpis, a sodales sit. Nullam ut dui tincidunt dui sodales, et eget ultricies cras ac mauris, et in sollicitudin quis et cum lacinia. Eget quis platea est pretium magna vitae, rhoncus luctus nulla vehicula pretium explicabo, turpis placerat. In ut posuere magna tortor non architecto, nisl cras eu lacus curabitur cras mauris. 

I believe you have seen the above effect everywhere. It is actually very easy to achieve and in this short article, we will see how to do it.

The float property
The float property is supported by any browser. It has 4 possible values:
1) right - the element floats on the right;
2) left - the element floats on the left;
3) none - the element doesn't float and it follows the normal page flow;
4) inherit - the element inherits the float from its parent.
Basically, if we want to use the float property we will create a class like:
float: right;
And then, we will assign the "floating" class to our object which will float on the right (like the image above).

Styling the element
We can then style the element. For example we can assign a margin around it:
margin: 0px 0px 5px 5px
At the same time, we can create a border around it, and add extra padding:
border: 1px solid #666666
padding: 2px
Or whatever you might like.

Caption for images and tables
If we want to add a caption to our image, we should create a container - like a div - and assign to that element the floating class. Every object inside the div will then be floating. Just put the image and the caption inside the div.
<div class="floating">
<img ...>
The float property can be applied to any element. When we have more than one small table, we can actually force the tables to stay one after the other. Just add to every table the floating class, and you will see the tables stay one after the other. A possible use is when we have a grid with navigation and a fluid design: you can assign different floating properties to the usual first, previous, next and last labels.

That's all for today. Happy coding.

0 thoughts:

Post a Comment

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.