Center child div in a parent div
3 ways to align center child div in parent div
by vaheed akhtar
HTML
<div class="parent1">
<div class="child1"></div>
</div>
<hr />
<div class="parent2">
<div class="child2"></div>
</div>
<hr />
<div class="parent3">
<div class="child3"></div>
</div>
<hr />
<div class="parent4">
Centered Text
</div>
<hr />
<div class="parent5">
<div class="child5"></div>
</div>
CSS
/* 1st way */
.parent1 {
background: darkcyan;
width: 200px;
height: 200px;
position: relative;
}
.child1 {
background: white;
height: 30px;
width: 30px;
position: absolute;
top: 50%;
left: 50%;
margin: -15px;
}
/* 2nd way */
.parent2 {
display: flex;
justify-content: center;
align-items: center;
background: darkcyan;
height: 200px;
width: 200px;
}
.child2 {
background: white;
height: 30px;
width: 30px;
}
/* 3rd way */
.parent3 {
position: relative;
height: 200px;
width: 200px;
background: darkcyan;
}
.child3 {
background: white;
height: 30px;
width: 30px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
/* 4rth way*/
.parent4 {
text-align: center;
height: 200px;
width: 200px;
background: darkcyan;
line-height: 200px;
color: white;
font-weight: 700;
}
/* 5th way*/
.parent5 {
display: grid;
place-items: center;
height: 200px;
width: 200px;
background: darkcyan;
}
.child5 {
background: white;
height: 30px;
width: 30px;
}