My Development Notes

Programming Made Easier


How to center divs exactly in the middle of the screen?

Here’s how it’s done using HTML and CSS.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <title>Document</title>
  </head>
  <body>
    <div class="container">
      <div class="box-one">Hello</div>
      <div class="box-two">How are you?</div>
    </div>
  </body>
</html>
.box-one {
  background-color: aqua;
  width: 500px;
  height: 200px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.box-two {
  background-color: bisque;
  width: 500px;
  height: 200px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

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

These are the basic codes to center the divs using CSS and you can further build up your own style from here.

Notice that we’ve used height: 100vh which is 100 percent of the viewport height so that we can precisely center the containers vertically. You can also try width: 100vw for the horizontal axis as well which works in a similar manner.


Posted

in

,

by

Tags:

Leave a Reply