CSS grid with fluid dimensions, shrink content while keeping their aspect ratio

124 views Asked by At

I want this auto grid to expand and shrink with the browser, while keeping the items centered in it, preserving their aspect ratio.

Ideally :

  • Pure CSS
  • Keeping grid in "auto" mode (no template)

(I know use-case might sound dumb, but this is pseudo-code of more complicated one)

html {
  height: 100%;
}

body {
  height: 100%;
  min-height: 100%;
  max-height: 100%;
}

.grid {
  height: 100%;
  display: grid;
}

.item {
  aspect-ratio: 1;
}

.item1 {
  grid-row: 1;
  grid-column: 1;

  /* Demo purpose */
  background-color: LightSalmon;
}
.item2 {
  grid-row: 1;
  grid-column: 2;

  /* Demo purpose */
  background-color: SlateBlue;
}
.item3 {
  grid-row: 2;
  grid-column: 1;

  /* Demo purpose */
  background-color: LightSeaGreen;
}
.item4 {
  grid-row: 2;
  grid-column: 2;

  /* Demo purpose */
  background-color: Plum;
}
<div class="grid">
  <div class="item item1">item1</div>
  <div class="item item2">item2</div>
  <div class="item item3">item3</div>
  <div class="item item4">item4</div>
</div>


Edit : what I want, visually

On a large screen :

|   [1][2]   |
|   [3][4]   |

On a narrow screen :

|      |
|[1][2]|
|[3][4]|
|      |

Without specifying any grid neither items size. (items expand to max width or max height, the other dimension accomodates accordingly)

1

There are 1 answers

0
Temani Afif On

rely on vmin and aspect-ratio

body {
  margin: 0;
  height: 100vh;
  display: grid;
  place-content: center;
}

.grid {
  height: 100vmin;
  aspect-ratio: 1;
  display: grid;
}


.item1 {
  grid-row: 1;
  grid-column: 1;

  /* Demo purpose */
  background-color: LightSalmon;
}
.item2 {
  grid-row: 1;
  grid-column: 2;

  /* Demo purpose */
  background-color: SlateBlue;
}
.item3 {
  grid-row: 2;
  grid-column: 1;

  /* Demo purpose */
  background-color: LightSeaGreen;
}
.item4 {
  grid-row: 2;
  grid-column: 2;

  /* Demo purpose */
  background-color: Plum;
}
<div class="grid">
  <div class="item item1">item1</div>
  <div class="item item2">item2</div>
  <div class="item item3">item3</div>
  <div class="item item4">item4</div>
</div>