How to position div element at the center of screen with CSS?

Spread the love

Sometimes, we want to position div element at the center of screen with CSS.

In this article, we’ll look at how to position div element at the center of screen with CSS.

How to position div element at the center of screen with CSS?

To position div element at the center of screen with CSS, we use flexbox.

For instance, we write

<html>
  <head> </head>
  <body>
    <div class="center-screen">I'm in the center</div>
  </body>
</html>

to put a div in the body element.

Then we write

.center-screen {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: center;
  min-height: 100vh;
}

to make the div a flex container with display: flex;

We make the flex direction vertical with flex-direction: column;

We center its contents vertically with justify-content: center;.

And we center its contents horizontally with align-items: center;.

Conclusion

To position div element at the center of screen with CSS, we use flexbox.

Leave a Reply

Your email address will not be published.