Centred widthless floats

Usually you can only float left or float right but if you have a group of buttons for a menu and you want them to be fluid in width then it would be nice to have them float in the centre of the page.

So how is this achieved?

The premise is simple and basically just involves a widthless float that is placed 50% from the left using position:relative. The nested inner element is then reversed and a negative relative position of 50% is applied. This has the effect of placing the element in the center. Relative positioning maintains the flow and allows other content to flow underneath.

The above demo should work in most modern browsers and will work in ie5 - 6 (untested in ie7 yet). (It probably won't work in ie5 mac but you may be able to achieve similar with display:inline-block.)

The drawbacks are mainly that when the floats wrap at shorter screenwidths then the element that has wrapped will not align to the center. That doesn't seem to be much of a problem to me but you may think differently. In a fixed width scenario there will of course be no need to wrap and should work fine.

There is also the problem that a horizontal scrollbar will appear at smaller screen sizes as well which is a shame which means that it best works with floats that have a combined width of less than 50% width of the main container.

The same techniques could most likely be applied to absolute elements as their behaviour of shrink-wrapping contents is the same as floats. However absolute elements would be removed from the flow so its not so useful

As usual use at your own risk and test thoroughly on the platforms you want to support. Any problems or improvements then email me at paul@pmob.co.uk although I can't guarantee to answer all emails.