Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css center div inside container?

Tags:

html

class

center

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.

like image 424
Marco Tck Avatar asked Sep 15 '13 16:09

Marco Tck


People also ask

How do I center a box in a CSS container?

Center Align Elements To horizontally center a block element (like <div>), use margin: auto; Setting the width of the element will prevent it from stretching out to the edges of its container.

How do I center a div inside a div using transform?

To horizontally center a block element, such as a div or graphic, use the left or right properties in combination with the transform property. The left property shifts the element's left edge to the middle of the page. The transform property is then used with the translate function.


Video Answer


1 Answers

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>
like image 102
Itay Avatar answered Oct 22 '22 14:10

Itay