Whenever I have to center a div. I always use one of the following 3 methods. The easiest method is the first one using flex.
Centering a div using flex
To center a div using flex, simply have a parent container and set it to display:flex
. Then use the flex properties of justify-content:center
and align-items:center
. This will perfectly center the children elements.
<div class="parent">
<div class="child">
Hi!
</div>
</div>
.parent{
display:flex;
justify-content:center;
align-items:center;
height:300px;
width:300px;
background-color:coral;
}
.child{
background-color:white;
}
Centering a div using grid
This way is almost the same as flex. The only difference is you set the display property to grid.
<div class="parent2">
<div class="child2">
Hi!
</div>
</div>
.parent2{
display:grid;
justify-content:center;
align-items:center;
height:300px;
width:300px;
background-color:purple;
}
.child2{
background-color:white;
}
Centering a div using absolute positioning
Using Absolute position is another way you can use to center a div.
To do it this way, you have to set the parent div to position:relative
. Then set the child div to position:absolute
. This makes it so we can control the child div relative to the parent div.
Now set the child div to be at top:50%
and left:50%
. This almost centers the div. To fully center it do transform:translate(-50%,-50%)
.
The final transform
is applied to the element itself and so it perfectly centers the child div.
<div class="parent3">
<div class="child3">
Hi!
</div>
</div>
.parent3{
position:relative;
height:300px;
width:300px;
background-color:olive;
}
.child3{
position:absolute;
top:50%;
left:50%;
transform:translate(-50%, -50%);
background-color:white;
}
Summary
3 ways you can use to center a div is using flex, grid, and absolute positioning.
I have a codepen for each 3 methods here.