CSS subgrid doesn't show gap for row

196 views Asked by At

I'm getting to know CSS' grid and subgrid. Working on a simple form with two columns and a few subgrids.

the parent grid has a gap: 1em - both te column and the row have show a 1em gap properly. But the subgrid shows only the gap for the column, the row gap does not work - it's 0. I can't figure out why... I can give the subgrid a gap-row: 1em, that works. Buth I prefer to solve the real problem and thereby learning what causes the real problem in the first place.

The html and CSS:

#gridContainer {
  display: grid;
  grid-template-columns: 1fr 3fr;
  gap: 1em;
  padding: 1em;
  justify-items: left;
}

.subgrid {
  display: grid;
  grid-template-columns: subgrid;
  grid-column: span 2;
  justify-items: left;
}
<div id="gridContainer">
  <div class="subgrid">
    <label for="nameCompanyDebt1">Naam onderneming:</label>
    <input type="text" id="nameCompanyDebt1" name="nameCompanyDebt1">
    <label for="companyDebt1">Zakelijke schuld</label>
    <input type="text" id="companyDebt1" name="companyDebt1">
  </div>
</div>

I'm aware that #gridContainer (the parent) does not have grid-template-rows. So there's no 'rows' to inherit. But gap: 1em counts for both the columns and rows, so that shouldn't be the issue, right? I did try to add grid-template-rows to #gridContainer, but this only causes the rows to overlap/stack.

I'm also aware of the fact that the parent (#subGrid) is and ID, and the subgrid (.subgrid) is a class. It seems to be no problem, as the columns work fine as is.

2

There are 2 answers

1
Alohci On BEST ANSWER

You're only subgriding the columns, so the entire subgrid fits inside the first row of the grid. So there is no gap to be displayed. To fix, subgrid the rows too.

Set grid-row to span as many rows as you've got in the subgrid.

#gridContainer {
  display: grid;
  grid-template-columns: 1fr 3fr;
  gap: 1em;
  padding: 1em;
  justify-items: left;
}

.subgrid {
  display: grid;
  grid-template-columns: subgrid;
  grid-template-rows: subgrid;
  grid-column: span 2;
  grid-row: span 2;
  justify-items: left;
}
<div id="gridContainer">  
  <div class="subgrid">
    <label for="nameCompanyDebt1">Naam onderneming:</label>
    <input type="text" id="nameCompanyDebt1" name="nameCompanyDebt1">
    <label for="companyDebt1">Zakelijke schuld</label>
    <input type="text" id="companyDebt1" name="companyDebt1">
  </div>
</div>

0
Niels On

Today I had an epiphany! the soluton to my problem was not a div with display: subgrid, but a div has diplay: contents!

This way all the children act as a child of the primary grid, but I can hide the div (and all its children) via its ID.