Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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;
}

Try

<someelement style="margin-left:auto;margin-right:auto">This is any element</someelement>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top