Center Elements of no Width
Centering block level elements is easy as you simply need to use margin:auto and a specified width (ie5.+ will need text-align:center applied to a parent element). However sometimes you want to center widthless elements that shrinkwrap their content and that is a little trickier.
Luckily there is a quite a simple method to do this and if you have already seen the vertical centering demo then you will be familiar with the technique used for ie where an element is placed 50% from the top and then the inner element is dragged back with a negative 50% top position to make it vertically center. Unfortunately only IE understands that method when used with vertical centering but if we apply it to horizontal centering then all modern browsers seem to work in the same way that ie does.
Code:
position:relative;
left:50%;
float:left;
clear:both;
margin:10px 0;
text-align:left;
}
.xinner{
border:1px solid #000;
padding:10px 20px;
position:relative;
left:-50%;
text-align:left;
}
I am using widthless floats so older browsers like IEMac will probably have problems with this but you should be able to effect a solution using display:inline-block instead for ie5mac. The reason for using widthless floats is that they will shrinkwrap the content which is what we want for this demo.
The outer element is placed 50% from the left using position:relative. We use position:relative so that we don't interrupt the vertical flow of the document. The inner element is then dragged backwards by 50% again using position:relative and this has the effect of perfectly centering our widthless element.
There is one problem in that a horizontal scrollbar will appear on the window if the centered element is more than half the size of the parent or existing window size. This can be cured by wrapping the whole lot in element that has overflow:hidden set and the scrollbars will disappear. Note that IE7 will also need position:relative added to this wrapper or it won't hide the scrollbars.
overflow:hidden;
position:relative;/* ie7 needs position:relative here*/
}
Here are a few examples using the techniques already mentioned.