How do you center align a div inside another div?

To center align a div inside another div, you can use the following steps:
Add a parent div element around the div that you want to center align.
Add the following CSS to the parent div:
.parent {
display: flex;
justify-content: center;
align-items: center;
}
- Add the following CSS to the child div that you want to center align:
.child {
display: inline-block;
}
This will center the child div within the parent div both horizontally and vertically.
Alternatively, you can use the following CSS to center align the child div horizontally within the parent div:
.parent {
text-align: center;
}
.child {
display: inline-block;
}
This will center the child div horizontally within the parent div, but it will not center it vertically.
You can also use the margin: auto
property to center align the child div within the parent div. For example:
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
This will center the child div both horizontally and vertically within the parent div.
Subscribe to my newsletter
Read articles from Udit Sharma directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
