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.
border:1px solid #000;
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.
position:relative;/* ie7 needs position:relative here*/
Here are a few examples using the techniques already mentioned.
Center elements of no specified width
This is some text of undefined width:
This is more text
This assumes text doesn't need to wrap
otherwise it will stretch full width
- List elements with no width
- List elements with no specified width with no specified width
- List elements no specified width
- List with no width
- elements with no specified width
This is the usual method of centering and centres a block level element centred using margin-left:auto and margin-right:auto on an element of specified width (px, perentage or em are fine). Note that ie5.+ would text-align:center on a parent in order to center this block level element. This method does need a width.
This text is centred using text-align:center
This block of short lines
Using the left:50% and left:-50% technique
border:1px solid #000;