How to center a div using flexbox in CSS?

To center a div using CSS flexbox, we have to first make the parent of the div element a flex container. To do this we have to apply display: flex; property on the parent element. This will make the parent of the div element a flex container.

The items that are inside of the flex container are called flex items.

Now, apply the justify-content: center; and align-items: center; properties on the same parent element which we made the flex container.

The justify-content property aligns all the flex items inside the flex container horizontally while the align-items property aligns all the flex items vertically.

Example:

.parent{
    display: flex;
    height: 400px;
    align-items: center;    /* aligns vertically */
    justify-content: center;  /* aligns horizontally */
    background: #9020e6;
}

.child{
    width: 150px;
    height: 150px;
    text-align: center;
    padding: 20px;
    background: cyan;
}

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.