2

I want to make a grid where all grid area parts are squares (grid column width = grid row height). It should be responsive and the device width should decide the 1fr width value (see below).

#gridParent {
     margin: 5rem 14rem;
}

#grid {
     grid-template-areas:
            "a a b b"
            "a a c d"
            "e e f f"
            "g g f f"
            "k l h h"
            "i i j j";

     grid-template-columns: repeat(4, 1fr);
     gap: 2rem;
}

<div id="gridParent">
    <div id="grid">
        <div class="gridItem"></div>
        <div class="gridItem"></div>
        <div class="gridItem"></div>
        <div class="gridItem"></div>
        <div class="gridItem"></div>
        <div class="gridItem"></div>
        <div class="gridItem"></div>
        <div class="gridItem"></div>
        <div class="gridItem"></div>
        <div class="gridItem"></div>
    </div>
</div>

now I would like to somehow calculate the rows height so the it is the same as the 1fr column width pixelwise(!)

grid-auto-rows: auto; is not working for me.

grid-auto-rows: 1fr; same goes for this.

Basically every grid area part ( every single "a" from the 2x2-"a" should be a sqare...) is that possible to do?

I also tried aspect ratio but this doesnt work with the 2x2 area parts and the 1x1 or 2x1 area parts in one row...

Temani Afif
  • 245,468
  • 26
  • 309
  • 415

1 Answers1

1

You can do it with aspect-ratio:

#grid {
  display: grid;
  grid-template-areas: 
   "a a b b" 
   "a a c d" 
   "e e f f" 
   "g g f f" 
   "k l h h" 
   "i i j j";
  grid-template-columns: repeat(4, 1fr);
  grid-auto-rows: 1fr; /* equal rows and ... */
  gap: 2rem;
}

/* ... set the ratio of only one square element */
.a {
 grid-area: a;
 aspect-ratio: 1;
}

.gridItem {
  background: red;
}
.b {grid-area:b}
.e {grid-area:e}
.f {grid-area:f}
/* and so on ..*/
<div id="gridParent">
  <div id="grid">
    <div class="gridItem a"></div>
    <div class="gridItem b"></div>
    <div class="gridItem e"></div>
    <div class="gridItem f"></div>
    <div class="gridItem"></div>
    <div class="gridItem"></div>
    <div class="gridItem"></div>
    <div class="gridItem"></div>
  </div>
</div>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
  • but is 1 vertical fr = 1 horizontal fr? because if not here is my problem: if you put content in the grid items, the vertical 1fr will "look" for the biggest height-value and apply it to all the others... and then there are no more squares but rectangles... or am i wrong? – Niklas Gemkow Mar 06 '23 at 01:36