CSS grid overflowing the page when using grid items with aspect-ratio

53 Views Asked by At

I have created a CSS grid layout in which grid items have aspect-ratio: 1 / 1. I don't know why this causing the grid to overflow the page.

Here is the code:

html,
body {
  margin: 0;
}

* {
  box-sizing: border-box;
}

.span-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
  height: 100vh;
}

.div {
  background-color: red;
  width: 100%;
  height: 100%;
  aspect-ratio: 1 / 1;
}
<div class="span-grid">
  <div class="div"></div>
  <div class="div"></div>
  <div class="div"></div>
  <div class="div"></div>
</div>

I would like the grid to fit on the screen while leaving empty space on the left and right of the screen. The boxes should be exact squares.

layout on higher resolution

1

There are 1 best solutions below

0
G-Cyrillus On

You need to scale it down. You may size the parent to a max-size that would be the smallest max-size of height/width to keep your square ratio within the browser view.

Here is an example using vmin value.

html {
  min-height: 100vh;
  display: grid;
  align-items: center;
}

body {
  margin: 0;
}

* {
  box-sizing: border-box;
}

.span-grid {
  aspect-ratio: 1; /* you can define your square here */
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-template-rows: repeat(2, 1fr);
  gap: 10px;
  max-height: 100vmin;
  margin: auto;
}

.div {
  background-color: red;
}
<div class="span-grid">
  <div class="div"></div>
  <div class="div"></div>
  <div class="div"></div>
  <div class="div"></div>
</div>