A grid layout with size, defined by size of its cells and gap

79 Views Asked by At

I have the following layout:

<div class="mygrid">
  <div class="first cell"></div>
  <div class="second cell"></div>
  <div class="third cell"></div>
  <div class="fourth cell"></div>
</div>

The styles are:

.mygrid
{
  background-color: gray;
  display: grid;
  gap: 1px;
    grid-template-columns: repeat(2, auto);
    grid-template-rows: repeat(2, auto);
    grid-template-areas:
        'first      second'
        'third      fourth';
}

.cell
{
  width: 40px;
  height: 40px;
  background-color: green;
}

(Here's the sample on CodePen).

I expected the grid container (div.mygrid) would have column width and row height defined by maximal dimensions of the cells, because I set them as repeat(2, auto). So, the total size would be 81px x 81px (40px * 2 + 1px of gap). But it actually has the same width as its parent.

How to achieve the described behavior?

Also, when I explicitly set the size of div.mygrid (width: 200px;), the gap property is ignored and the cells are distributed evenly. Why and how to fix this?

0

There are 0 best solutions below