floatitis pt2

In my previous article on floats I explained the back story of the float. As promised, the next couple of articles will list alternative methods to avoid the use of the float property where possible. None of these methods are fool proof, they all have their own advantages and disadvantages and in the end there will be no effective cure against the abuse of floats. But hopefully, you'll have a few more tools to avoid problems.

bottles aligned to the right

kiss

css is considered to be difficult, but we don't always make it easy on ourselves either. The float property is usually acquired pretty early on in the css learning process and is considered to be one of the only tools to position elements. Sadly, other options are never learned, often overlooked or even completely forgotten. And so, we end up with clearfix littered html code and browser bugs everywhere.

The first alternative I'll present is extremely easy and transparent. Introducing the powerful and incredibly simple css property: text-align.

using text-align

.more {text-align:right;} .more a {...}

The use of text-align is pretty limited as an alternative for the float, but there are a fair few well-defined examples where it can really help you out.

The text-align property works on inline content, so don't expect to start positioning whole blocks of content using it. On the other hand, it is pretty useful for positioning small pieces of inline content. The example given above is ideal for 'more >' links and similar cases. These kind of links are often positioned to the right of the content. You have several options to get them there, including floating the <a> tag (which will result in clearfixing the parent element).

To make this solution work well using the text-align property, it's best to add an extra structural element (the .more class referenced in the css). It is possible to set the <a> tag itself to display:block; but that will influence the click area of your link in less than favorable ways. I usually add an extra div element around the link, which is actually nothing to be ashamed of. It does the trick and brings some added structural relevance.

That's all there is to it really, just add a text-align property on your parent element and the inline context will position itself accordingly. Much easier than floating, no?

conclusion

Next time you have to position a simple link or small snippet of inline content, consider using the text-align instead of a float property, even if it requires a little extra markup. From a structural point of view the mark-up won't hurt (as it has structural relevance) and possible float issues can be avoided.

It's a simple method, it requires little skill to use, it's browser proof, but often you see people still reaching for the float property. Hopefully this will change some day.