19

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.

Marco Tck
  • 261
  • 1
  • 3
  • 11

1 Answers1

40

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

Code snippet

div {
    border: 2px solid black;
    margin: 10px;
}

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

.centered {
  text-align: center;
}
<div class="MyContainer">
    <div>Inner DIVs are centered
        <div class="centered">Here the text is also centered</div>
    </div>
</div>
Itay
  • 16,601
  • 2
  • 51
  • 72
  • 1
    That won't center the div. `text-align` influences the inline content of an element, a div is a block. – Quentin Sep 15 '13 at 16:54
  • I understand from the OP that he wants to replace `align="center"` with a CSS definition. – Itay Sep 15 '13 at 16:55
  • text-align only centers the text but the div itself remains at the left of the container. – Marco Tck Sep 15 '13 at 16:55
  • Yup !! that's exactly what I wanted, thank you very much !! I just wonder why CSS 3 doesn't have an equivalent command for HTML "align" – Marco Tck Sep 15 '13 at 17:09
  • Well this is the CSS way of doing this... Nevertheless this is an interesting question – Itay Sep 15 '13 at 17:12