How to horizontally and vertically center a div in HTML using CSS

Have you been running into problems of centering a div both horizontally and vertically? There are a lot of ways to resolve the issue. One of such methods is using absolute and relative positions on the child div and parent div.

Confused on how to go about it? Don't worry. Below is a step by step approach to it using an example.

HTML code

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>How to center a div</title>
    <link rel="stylesheet" href="./css/index.css" />
  </head>
  <body>
    <div class="parent-div">
      <div class="child-div"></div>
    </div>
  </body>
</html>

In the code above, we have the parent-div which encloses a child-div. Let's add some styles using CSS.

##CSS code

* {
  box-sizing: border-box;
}

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

.parent-div {
  height: 100%;
  position: relative;
  width: 100%;
}

.child-div {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 400px;
  min-height: 300px;
  border: 1px solid black;
}

Code Explanation

Here is an explanation to the code above:-

If a child element is given the position: absolute, the parent element should be given a position: relative, width and height so as to be able to place the child element in any position on the page or else the styles wouldn't be applied on the child element.

Following this rule, we gave the parent a width, height and position: relative. We gave the child element a position of absolute which keeps it floating.

Next, we gave it a top value of 50% which puts at the center of the page topside, a left position of 50%, a transform property of -50% for the X-axis and -50% for the Y-axis which eventually puts it at the middle.

Output

Screenshot from 2020-11-13 22-41-41.png

Conclusion

The width and min-height can be adjusted to fit your work. You can try out different values too.