How to Center Align Child Element to its Parent Div

By Mohammed Rashid •  February 24th, 2021 • 
CSS

In this html tutorial, let’s learn how to align the child elements centrally to its parent div using CSS.

If you prefer video tutorials then watch the following YouTube tutorial.

The child elements of a parent can be aligned using three style properties- display, align-center, and justify-content. These properties should be applied to the parent element.

The value of the display should be made flex. You can learn more about flexbox here. The align-center property helps to align the child elements vertically whereas justify-content aligns the child elements horizontally.

.parent {
        width: 500px;
        height: 500px;
        background-color: blue;
        display: flex;
        align-items: center;
        justify-content: center;
      }

Following is the complete HTML example.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Centering Elements in div</title>
    <style>
      .parent {
        width: 500px;
        height: 500px;
        background-color: blue;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .child {
        width: 200px;
        height: 200px;
        background-color: red;
      }
    </style>
  </head>
  <body>
    <div class="parent">
      <div class="child"></div>
    </div>
  </body>
</html>

Following is the output.

You can see, the child element red div is placed at the exact center of the parent div.

Mohammed Rashid

Keep Reading