How to center an element/a div horizontally and vertically?

Problem:

You have a div element. you need to center it horizontally and vertically in the browser. The HTML codes are:

<div class="container"><p>this is centered</p></div>

Solution:

There are multiple ways to solve this problem.

Method 1:

CSS:

.container{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
}

Explanation:

When you set “position:absolute”, the element becomes fixed in the browser. “top:50%” makes the top edge of the element lie in the middle vertically in the browser. “left:50%” allows left edge of the element to starts from the center horizontally. Now, we have to move up and move left to center the whole element. This is done by “transform” property. translateX(-50%) moves the element left 50% of its width. Accordingly, translate(-50%) moves the element up 50% of its height.

Method 2:

Using flexbox method:

html, body, .container {
    height: 100%;
}
.container {
    display: flex;
    align-items: center;
    justify-content: center;
}

Explanation:

The align-items: center for vertical centering and justify-content: center for horizontal centering. Height of the html, body, and container sets to 100% so that it takes the browser’s full screen.

Method 3:

CSS:

html,body{height:100%;}
body{display:table; width:100%; text-align:center;}
.container{
    display: table-cell;
    vertical-align: middle;
}

Explanation:

“Text-align:center” is used to make it horizontally centered, “vertical-align:middle” is used to make it vertically centered. “display:table” makes the display as table and the child element is made table-cell.

Method 4:

CSS:

html, body, .container {
    height: 100%;
}
.body {
    position: relative;
    text-align: center;
}
.container {
    position: absolute;
    top: 50%;
    left: 0;
    right: 0;
    margin-top: -9px;
}