htmlcsscss-gridsubgrid

CSS Grid layout with equal width sections columns and sections with borders/margins


I am looking to have a grid layout (3 columns) of repeating sections. I want the sections to have border and margins as well as have equal width columns throughout all sections. I have gotten most of the way there but am battling between no border/margin using display: contents; or unequal widths. Is what I am asking for css subgrid? (poorly supported), is there another way or am I left to apply border/margin to children?

.grid {
  display: grid;
  grid-template-columns: auto auto 1fr;
  padding: 10px;
  border: 2px solid red;
}

.sectionWrap {
  display: contents;
  border: 3px solid purple;
  margin: 6px;
}

.c1,
.c2,
.c3 {
  border: 1px solid blue;
}
<div class="grid">
  <div class="sectionWrap">
    <div class="c1">
      shorter text
    </div>
    <div class="c2">
      2
    </div>
    <div class="c3">
      3
    </div>
  </div>
  <div class="sectionWrap">
    <div class="c1">
      longer text...............
    </div>
    <div class="c2">
      2
    </div>
    <div class="c3">
      3
    </div>
  </div>
</div>
<span> unfortunately missing my border and margin using display: contents.


Solution

  • Margin can be replaced with gap and border with individual border on your elements:

    .grid {
      display: grid;
      grid-template-columns: auto auto 1fr;
      row-gap:12px;
      padding: 12px;
      border: 2px solid red;
    }
    
    .sectionWrap {
      display: contents;
    }
    
    
    .c1 {
      border:3px solid purple;
      border-right:1px solid blue;
    }
    .c2 {
      border:3px solid purple;
      border-right:1px solid blue;
      border-left:1px solid blue;
    }
    .c3 {
      border:3px solid purple;
      border-left:1px solid blue;
    }
    <div class="grid">
      <div class="sectionWrap">
        <div class="c1">
          shorter text
        </div>
        <div class="c2">
          2
        </div>
        <div class="c3">
          3
        </div>
      </div>
      <div class="sectionWrap">
        <div class="c1">
          longer text...............
        </div>
        <div class="c2">
          2
        </div>
        <div class="c3">
          3
        </div>
      </div>
    </div>
    <span>