How to center a div using flexbox?


Flexbox has given us a very nice way to center HTML elements without doing any kind of CSS or JS hack. Let’s have a look at how we can center a div using flexbox.

Below is the complete HTML code for the above image.

HTML
<!DOCTYPE html>
<html>

<head>
    <title>Center div using flexbox</title>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <div class="parent flex-center">
        <div class="child flex-center">
            <span>I'm centered</span>
        </div>
    </div>
</body>

</html>

CSS

html,
body {
    height: 100%;
    margin: 0;
    padding: 0;
}

body {
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
    font-size: 24px;
}

.flex-center {
    display: flex;
    align-items: center;
    justify-content: center;
}

.parent {
    height: 100%;
    background-color: #066163;
}

.child {
    background-color: #CDBE78;
    width: 200px;
    height: 200px;
    border: solid 1px #CDBE78;
    border-radius: 4px;
    padding: 5px;
}

Here, we have created a class .flex-center which sets the CSS properties of the element whose child we want to be centered. Read more about flex here.