How to center a <div> using the Flexbox property of CSS?


We can center a <div> in css using justify-content property and align-item property of flexbox. They are popular because they are responsive and easy to use. In this article, we shall learn how to center <div> using the Flexbox properties.

Use The align-items And The justify-content Property

The most popular method to center the div using the flexbox is the combination of justify-content and align-items properties of flexbox.

  • The justify-content property would center align the div horizontally.

  • The align-items property center aligns the div vertically.

If you want to center align only in one direction, i.e., either vertically or horizontally, we should use only one among the properties we mentioned.

Use the align-items and the justify-contents to center align the child horizontally and vertically.

Example

<!DOCTYPE html>
<html lang="en">
<style>
   .parent{
      border: 2px solid green;
      height:30vh;
      width:30vw;
      display: flex;
      flex-direction: row;
      justify-content: center;
      align-items: center;
      background-color: orange;
   }
   .child{
      border: 2px solid red;
      height:10vh;
      width:10vw;
      background-color: yellow;
   }
</style>
</head>
<body>
   <div class="parent">
      <div class="child">
         This is the child element.
      </div>
   </div>
</body>
</html>
  • In the code, the parent element is a green-bordered orange box with a height of 30% of the viewport height and a width of 30% of the viewport width.The parent is centered both horizontally and vertically with the help of "display: flex", "flex-direction: row", "justify-content: center" and "align-items: center."

  • To use the align-items and justify-content, we first need to declare the element to be a flexbox using the display property. The child element is a red-bordered yellow box with a height of 10% of the viewport height and a width of 10% of the viewport width, which is placed inside the parent element.

Conclusion

In this article, we have understood how to center a <div> using the flexbox property of CSS. We only need to use the justify-content and the align-content property of flexbox to achieve the same.

Updated on: 13-Mar-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements