Search code examples
htmlcsscss-gridvertical-alignment

How do I vertically center a grid container in CSS?


All I want in life is this grid of squares to be in the center of the page on both axes and it's driving me nuts. It is centered on the x-axis, but I cannot for the life of me figure out how to center it along the y-axis. How can I do this while still maintaining responsiveness? You will see that I created a div called margin-help to try to get it to work but to no avail. Here is a link to the codepen, the code itself, as well as a screenshot of what I'm dealing with. All help is very much appreciated. Thanks! https://codepen.io/Brianna-Drew/pen/WNyOoWJ

@font-face {
  font-family: This Is The Future;
  src: url(fonts/This\ Is\ The\ Future.ttf);
}

html,
body {
  min-height: 100%;
}

body {
  margin: 0;
  text-align: center;
  background-color: black;
  font-family: This Is The Future;
  display: block;
  height: 100vh;
  padding-top: auto;
  padding-bottom: auto;
}

.margin-help {
  display: flex;
  margin: auto;
}

.grid {
  display: grid;
  margin: auto;
  grid-template-columns: auto auto auto auto;
  grid-template-rows: auto auto auto auto;
  justify-content: center;
  align-content: center;
  gap: 10px;
}

.squares {
  display: flex;
  background-color: white;
  max-width: 100px;
  width: 15vw;
  max-height: 100px;
  height: 15vw;
  align-items: center;
  justify-content: center;
}
<!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>SENSUS</title>
    <link href="styles.css" rel="stylesheet" />
  </head>
  <body>
    <div class="margin-help">
      <div class="grid">
        <div class="squares" id="a1"></div>
        <div class="squares" id="b1"></div>
        <div class="squares" id="c1"></div>
        <div class="squares" id="d1"></div>
        <div class="squares" id="a2"></div>
        <div class="squares" id="b2"></div>
        <div class="squares" id="c2"></div>
        <div class="squares" id="d2"></div>
        <div class="squares" id="a3"></div>
        <div class="squares" id="b3"></div>
        <div class="squares" id="c3"></div>
        <div class="squares" id="d3"></div>
        <div class="squares" id="a4"></div>
        <div class="squares" id="b4"></div>
        <div class="squares" id="c4"></div>
        <div class="squares" id="d4"></div>
      </div>
    </div>
    <script src="script.js"></script>
  </body>
</html>

enter image description here


Solution

    1. Remove div with class = margin-help

    2. In css, add the following styles for body tag

      display: flex; justify-content: center; align-items: center;

    justify-content will center horizontally. align-items will center vertically