css center div inside container?

Marco Tck picture Marco Tck · Sep 15, 2013 · Viewed 47.3k times · Source

This HTML code works:

<div class="MyContainer" align="center">
    <div>THIS DIV IS CENTERED</div>
</div>

But I would like to do it at the css of the container, something like:

.MyContainer{
    align: center;
}

So all my containers will center the divs inside.

Answer

Itay picture Itay · Sep 15, 2013

The CSS property for the text align is called text-align not align like in the inline DOM attribute.


If you want to center a block element (like div, p, ul, etc...) itself you need to set its width and set the horizontal margins to auto.

For example, the following code will make every div inside an element with the MyContainer class 80% the size of its parent and center it in the middle of its container.

.MyContainer div {
    margin: 0 auto;
    width: 80%;
}

jsFiddle Demo