Aphiwad Chhoeun

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:

  1. Using Flexbox: You can use the display: flex property and align-items: center and justify-content: center properties.
.parent { display: flex; align-items: center; justify-content: center; }

<div class="parent">
  <div class="child">I'm centered!</div>
</div>
  1. Using Grid: You can use the display: grid property and place-items: center property.
.parent { display: grid; place-items: center; }

<div class="parent">
  <div class="child">I'm centered!</div>
</div>
  1. Using Absolute Positioning: You can use the position: absolute property to position the div element within the parent container and set the top, left, right and bottom properties to 50%, and transform: 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>
  1. 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>