DEV Community

Usama Jamil
Usama Jamil

Posted on

Simplest way to center a div

As a web developer sometimes centering a div is the toughest job ever.
So I am here with a coolest and the easiest way to center a div.
So here's the html code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
    <style>
    </style>
</head>
<body>
    <div id="parentContainer">
        <div id="childContainer"></div>
    </div>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

I have made two divs in the body. One is with id parentContainer and the other one is childContainer.
Let me share you the css code.

#parentContainer{
    width: 400px;
    height: 400px;
    background-color: brown;
}
#childContainer{
    width: 100px;
    height: 100px;
    background-color: black;
}
Enter fullscreen mode Exit fullscreen mode

I just simply gave height of 400px and width of 400px and the background-color brown to the parentContainer
Similarly I gave height of 100px and width of 100px and the background-color black to the childContainer
Our div is not centered yet, lemme show you guys

Image description

Position property in css is used to set how element is positioned on the page. The default value for position element is static. The other values for position element are relative, absolute, fixed and sticky.
Now if we set position: absolute; to a DOM element it becomes absolute with respect to whole page. This would be useful if we want to center the div with respect to whole page.

On the other hand giving position: relative; to the parent element, makes the children element (with position: absolute;) absolute, related to the parent element , not to the whole page.
Now if we mention top: 0;, left: 0;, bottom: 0; and right: 0;, with margin: auto; and position elements in containers, it centers our div.

#parentContainer{
    position: relative;
    width: 400px;
    height: 400px;
    background-color: brown;
}
#childContainer{
    position: absolute;
    width: 100px;
    height: 100px;
    background-color: black;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    margin: auto;
}
Enter fullscreen mode Exit fullscreen mode

Image description

Congratulations You have set your div to center.

Top comments (0)