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.
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
is centred
Using the left:50% and left:-50% technique
.outer{
position:relative;
left:50%;
float:left;
clear:left;
margin-bottom:10px;
}
.inner{
border:1px solid #000;
padding:10px 20px;
position:relative;
left:-50%;
text-align:left;
}

