How to center a div inside another div using CSS?

Centering a div inside another div is a common problem that most of the developers generally face. However, centering a div in CSS is not that difficult.

There are several methods that can help us center a div inside another div element. Let’s discuss a few easy methods.


Center a div inside another div using CSS flexbox

To center a div inside another div using CSS flexbox, set the display property to flex for the parent div element. This will make the parent div element a flex container.

Once it’s done apply the justify-content: center; and align-items: center; properties on the parent div element. The justify-content property aligns the child elements horizontally while the align-items property aligns the child elements vertically.

Try out the example given below:

Example:

.parent{
    display: flex;
    height: 400px;
    align-items: 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;
}

Center a div inside another div using CSS grids

Centering a div inside another div using CSS grids is similar to centering it using CSS flexbox. The only difference is that here you have to set the display property to grid. Doing so will make the parent div a grid container which can help us center all its child elements.

Here, to align div vertically, we use the align-content property. The justify-content property remains the same.

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;
}

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.

    View all posts