cssgridcss-grid

CSS Grid row/column gap on specific elements?


I have created the grid below using CSS Grid and I am wondering if it's possible to have a gap only between specific elements within the grid, rather than applying a universal gap to all grid elements. Here's what I have right now:

body {
  margin: 40px;
}

.wrapper {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: [col] 100px [col] 100px [col] 100px;
  grid-template-rows: [row] auto [row] auto [row] ;
  background-color: #fff;
  color: #444;
}

  .box {
    background-color:#444;
    color:#fff;
    padding:20px;
    font-size:150%;
  }
    .a {
      grid-column: col / span 2;
      grid-row: row 1 / 3;
    }
    .b {
      grid-column: col 3 / span 1;
      grid-row: row ;
    }
    .c {
      grid-column: col 3 / span 1;
      grid-row: row 2 ;
    }
    .d {
      grid-column: col / span 1;
      grid-row: row 3;
    }
    .e {
      grid-column: col 2 / span 1;
      grid-row: row 3;
    }
    .f {
      grid-column: col 3 / span 1;
      grid-row: row 3;
    }
    .g {
      grid-column: col / span 1;
      grid-row: row 4;
    }
    .h {
      grid-column: col 2 / span 1;
      grid-row: row 4;
    }
    .i {
      grid-column: col 3 / span 1;
      grid-row: row 4;
    }
<div class="wrapper">
  <div class="box a">A</div>
  <div class="box b">B</div>
  <div class="box c">C</div>
  <div class="box d">D</div>
  <div class="box e">E</div>
  <div class="box f">F</div>
  <div class="box g">G</div>
  <div class="box h">H</div>
  <div class="box i">I</div>
</div>

I would like to remove the gap between the top 2 rows on the right side and between each cell on the rows below that. I would like to keep the cells broken up as they are now because the layout will be different on desktop. Here's a graphical representation of what I'm going for:

enter image description here


Solution

  • It's impossible to change the gap on specific elements.

    However, you can reference specific grid item with grid-item:nth-child(n) and set negative margins to it.

    For example, with a class of picture-1 it may look like this in the CSS file:

    .picture-1:nth-child(3) {
      margin-bottom: -50px;
    }