tags:

views:

344

answers:

3

Let's say you have the following chunk of code:

<div id="container">
<someelement>This is any element.</someelement>
</div>

What's the best CSS I could use to horizontally center "someelement" within its containing div?

+2  A: 

Try

<someelement style="margin-left:auto;margin-right:auto">This is any element</someelement>
JaredPar
+10  A: 

JaredPar has the right idea, but here's a cleaner way to do what you're looking for ;)

#container {
    text-align: center;
}

#container someelement {
    margin: 0 auto;
    text-align: left;
}
ojrac
Why 0 auto vs auto? Not a CSS buff so the obvious may be the answer
JaredPar
Jared: 0 auto is cleaner than doing margin-left/margin-right separately. Functionally they're the same (at least, I'm 99% sure they are).
mabwi
0 is for top and bottom margins and auto for left and right margins
allesklar
+1 for giving the standard method
Alex Baranosky
+3  A: 

if your <someelement> is an inline element (i.e defaults to display: inline) apply text-align: center to its container. If <someelement> is a block element set left and right margin to auto and remember to set a width (block elements default to take all available horizontal space unless a width is stated explicitly). You may have to use both methods if you want it to work in IE 5.5 and below too.

djn