Center align with float left or right

Some said that you cannot centre floated elements but this is not quite true. It’s true that usually you can only float left or float right but if you have a group of buttons (for example it is menu) and you want them to be fluid in width then it would be nice to have them all float in the centre of the page. There is no problem if the floats have a width because you can then ascertain the main parents width and use margin:auto to center the whole block. However that means that the floats cannot be a fluid width (i.e. shrinkwrap their content) or you would have to class each individual element and apply a different width to each which is a little unsatisfactory.

#buttons{
float:right;
position:relative;
left:-50%;
text-align:left;
}
#buttons ul{
list-style:none;
position:relative;
left:50%;
}

#buttons li{float:left;position:relative;}/* ie needs position:relative here*/

#buttons a{
text-decoration:none;
margin:10px;
background:red;
float:left;
border:2px outset blue;
color:#fff;
padding:2px 5px;
text-align:center;
white-space:nowrap;

}
#buttons a:hover{ border:2px inset blue;color:red;background:#f2f2f2;}
#content{overflow:hidden}/* hide horizontal scrollbar*/

I tested it on ie7-9, firefox and chrome. It works 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

3 × 2 =