Home > Software engineering >  How do I vertically center a grid container in CSS?
How do I vertically center a grid container in CSS?

Time:11-14

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! enter image description here

CodePudding user response:

  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

CodePudding user response:

Changed the body display to flex and it worked!

CodePudding user response:

update css for margin-help class

@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;
  width: 100%;
  height: 100vh;
  justify-content: center;
  align-items: center;
}

.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;
}
and wrap the grid with div

<!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 >
      <div>
        <div >
          <div  id="a1"></div>
          <div  id="b1"></div>
          <div  id="c1"></div>
          <div  id="d1"></div>
          <div  id="a2"></div>
          <div  id="b2"></div>
          <div  id="c2"></div>
          <div  id="d2"></div>
          <div  id="a3"></div>
          <div  id="b3"></div>
          <div  id="c3"></div>
          <div  id="d3"></div>
          <div  id="a4"></div>
          <div  id="b4"></div>
          <div  id="c4"></div>
          <div  id="d4"></div>
        </div>
      </div>
    </div>
    <script src="script.js"></script>
  </body>
</html>

  • Related