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.
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.
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.
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%;
}
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With