Aligning Block Elements in CSS
The margin property is used not only to set margins, but also to center block elements. To do this, the right and left margins should be set to auto.
In the example below, the inner block will be centered:
<div class="parent">
<div class="child"></div>
</div>
.parent {
border: 1px solid red;
}
.child {
height: 100px;
width: 200px;
border: 1px solid green;
margin: 10px auto;
}
:
Please note that this method only allows you to center block elements, only horizontally, and only if they have a width assigned to them.
If we need different top and bottom margins margin, we can write it like this:
.child {
margin: 30px auto 10px auto;
}
You can also rewrite it using three values: the first will set the top indent, the third will set the bottom indent, and the second will set the value auto for the right and left indents:
.child {
margin: 30px auto 10px;
}
Repeat the page as shown, making sure the green blocks are centered on their parent: