Categories
JavaScript Answers

How to place div element at center of screen with CSS?

Spread the love

To place div element at 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 add a div.

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;.

Then we set its flex direction to vertical with flex-direction: column;.

We horizontally center its content with align-items: center;.

And we vertically center its content with justify-content: center;.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *