0

I am trying to center a grid display within an element 100% the size of a page, while making a space around the whole grid. I have tried auto margins, but the grid is sticking to the top of the parent. When adding manual margins, the body pushes down the grid's parent element acting as the margin of the grid. I have also tried another div within the parent element spacing the grid halfway down. Is there any way to do this cleaner (without the spacer)?

HTML:

<html>
  <body>
    <main>
      <div class="spacer"></div>
      <div class="grid">
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
      </div>
    </main>
  </body>
</html>

CSS:

html, body {
  height: 100%;
  width: 100%;
}

main {
  height: 100%;
  width: 100%;
}

.spacer {
  height: 10%;
}

.grid {
  display: grid;
  height: 80%;
  width: 90%;
  grid-template: 1fr 2fr 1fr / 1fr 2fr 1fr;
  margin: auto;
}

JSFIDDLE: https://jsfiddle.net/593Lovxw/22/

1 Answers1

0

Try this:

html, body {
  height: 100%;
  width: 100%;
}

main {
  background: #f00;
  height: 100%;
  width: 100%;
  display: flex;
  vertical-align: center;
}

.spacer {
  background: orange;
  height: 10%;
}

.grid {
  display: grid;
  height: 80%;
  width: 90%;
  grid-template: 1fr 2fr 1fr / 1fr 2fr 1fr;
  margin: auto;
}

.grid div {
  background: #00f;
  border: thick solid black;
}
<html>
  <body>
  <div class="spacer"></div>
    <main>
      <div class="grid">
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
      </div>
    </main>
  </body>
</html>
Abolfazl Mohajeri
  • 1,734
  • 2
  • 14
  • 26
  • "Try this" is not an acceptable answer on stack. Please put some effort into explaining your answer, including how and why it solves the issue. – Claire Jun 19 '18 at 19:50
  • Thanks, it seems that flexbox's vertical and horizontal alignment works best for this kind of thing. – Brendaneus Nov 12 '19 at 13:02