Home > Software design >  CSS Grid - Stretch & wrap row based on adjacent siblings with a flat DOM
CSS Grid - Stretch & wrap row based on adjacent siblings with a flat DOM

Time:01-18

Trying to figure out how to get a grid layout with stretching rows based on number of adjacent siblings. Open to grid/flexbox/(other) solutions in SCSS or CSS.

desired view

The list is generated from some configs. I have no idea how long, how many, or what order I may receiving the items. There are some rules like, item-type-a is always a full row and item-type-b should stretch to fill the row with a maximum of 3 per row.

Is this possible with pure CSS?

  <div >
    <div >Type A</div>
    <div >Type B</div>
    <div >Type B</div>
    <div >Type A</div>
    <div >Type B</div>
    <div >Type B</div>
    <div >Type B</div>
    <div >Type B</div>
    <div >Type A</div>
  </div>

To make the picture I used this CSS but need to a way to remove item-type-c & item-type-d

<style>
  .container {
    background: white;
    border: dashed red 1px;
    padding: 24px;
    max-width: 1080px;
    display: grid;
    gap: 2rem 2rem;
    grid-template-columns: repeat(12, 1fr);
  }

  .item {
    background: lightgray;
    min-width: 200px;
    min-height: 100px;

    display: grid;
    place-items: center;
    text-align: center;

    font-size: 24px;
    font-family: 'Helvetica';
  }

  .item-type-a {
    grid-column: auto / span 12;
  }

  .item-type-b {
    grid-column: auto / span 6;
  }

  .item-type-c {
    grid-column: auto / span 4;
  }

  .item-type-d {
    grid-column: auto / span 12;
  }
</style>

CodePudding user response:

.container {
  background: white;
  border: dashed red 1px;
  padding: 24px;
  max-width: 1080px;
  display: flex;
  flex-wrap: wrap;
  gap: 2rem 2rem;
}

.item {
  background: lightgray;
  min-width: 200px;
  min-height: 100px;
  display: grid;
  place-content: center;
  text-align: center;
  font-size: 24px;
  font-family: 'Helvetica';
  flex: 1 0 calc(33% - 2rem);
}

.item-type-a {
  flex-basis: 100%;
}
<div >
  <div >Type A</div>
  <div >Type B</div>
  <div >Type A</div>
  <div >Type B</div>
  <div >Type B</div>
  <div >Type A</div>
  <div >Type B</div>
  <div >Type B</div>
  <div >Type B</div>
  <div >Type A</div>
  <div >Type B</div>
  <div >Type B</div>
  <div >Type B</div>
  <div >Type B</div>
  <div >Type A</div>
  <div >Type B</div>
  <div >Type B</div>
  <div >Type B</div>
  <div >Type B</div>
  <div >Type B</div>
  <div >Type B</div>
  <div >Type B</div>
  <div >Type A</div>
  <div >Type A</div>
</div>

  •  Tags:  
  • Related