How to center a div using grid in CSS?

If you want to center a div both horizontally and vertically, a CSS grid is the best choice.

In order to center a div using CSS grids, we have to make use of the align-content and the justify-content property. The justify-content property centers the element horizontally while the align-content property aligns it vertically inside the grid container.

Example:

.parent{
   display: grid;
   height: 400px;
   align-content: center;    /* aligns vertically */
   justify-content: center;  /* aligns horizontally */
   border: 2px solid red;

}
.child{
   width: 100px;
   height: 100px;
   text-align: center;
   padding: 20px;
   background: cyan;
   border: 1px solid;
}

In the above example, each element inside the parent grid container will always be perfectly centered.


Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.