skip to Main Content

I want to make a dashboard like view, where I use the CSS Grid-Layout as base. I want to have 16 columns distributed over the whole length of the screen (should be responsive). And afterwards the cell height should be determined by the width of the cell, so that the cells are squares. The problem is, that I want to have some cell spans to span the element over multiple cells. As example I want a element which is 2×1 cells big.

So I have the basic grid layout:

.grid-container {
    display: grid;
    grid-template-columns: repeat(16, 1fr);
    grid-auto-rows: var(--tile-unit);
    gap: var(--tile-gap);
    align-content: start;
}

.grid-item {
    background: light-gray;
    border-radius: 10px;
}

And some classes to span the elements over multiple columns or rows:

.width-unit-2 {
    grid-column-end: span 2;
}

.height-unit-2 {
    grid-row-end: span 2;
}

Now, I tried it with the aspect-ratio of an element. This works fine for 2×1 elements, but if I want an element which is 2×2 i can’t just define the aspect ratios in the respective classes, i would have to define a separate class for this case.

Is there a way to have grid cells to be squared without this aspect-ratio?

2

Answers


  1. The aspect-ratio of the square is actually 1x1, then CSS sets its size to whether height or width

    Login or Signup to reply.
  2. Your question is very confusing and seems to be contradictory. This is what I came up with that creates squares based on the width.

    • Remove grid-auto-rows
    • Remove align-content (no effect)
    • Add aspect-ratio: 1 to the grid items
    • Add aspect-ratio: auto to the span classes
    section {
      display: grid;
      grid-template-columns: repeat(16, 1fr);
      gap: 1em;
    }
    
    div {
      aspect-ratio: 1;
      background-color: lightgray;
      border-radius: 10px;
    }
    
    .width-unit-2 {
      grid-column-end: span 2;
      aspect-ratio: auto;
    }
    
    .height-unit-2 {
      grid-row-end: span 2;
      aspect-ratio: auto;
    }
    <section>
      <div class="width-unit-2 height-unit-2"></div>
      <div class="height-unit-2"></div>
      <div class="width-unit-2"></div>
      <div class="height-unit-2"></div>
      <div></div>
      <div class="width-unit-2"></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div class="height-unit-2"></div>
      <div class="width-unit-2 height-unit-2"></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div class="width-unit-2"></div>
      <div></div>
      <div></div>
      <div></div>
    </section>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search