Center a div element horizontally and vertically
Centering any div element with simple CSS tricks
There are several ways to center a div element horizontally and vertically within its parent container. Here are a few common methods:
- Using Flexbox: You can use the
display: flexproperty andalign-items: centerandjustify-content: centerproperties.
.parent { display: flex; align-items: center; justify-content: center; }
<div class="parent">
<div class="child">I'm centered!</div>
</div>
- Using Grid: You can use the
display: gridproperty andplace-items: centerproperty.
.parent { display: grid; place-items: center; }
<div class="parent">
<div class="child">I'm centered!</div>
</div>
- Using Absolute Positioning: You can use the
position: absoluteproperty to position the div element within the parent container and set thetop,left,rightandbottomproperties to50%, andtransform: translate(-50%, -50%)properties.
.parent { position: relative; } .child { position: absolute; top: 50%; left:
50%; transform: translate(-50%, -50%); }
<div class="parent">
<div class="child">I'm centered!</div>
</div>
- Using Text Align and Line Height: This method is used when you want to center the div element horizontally and vertically with the text inside the div, and you know the height of the parent element.
.parent { text-align: center; line-height: 200px; }
<div class="parent">
<div class="child">I'm centered!</div>
</div>