Flexbox alternate row style

Viewed 261

i have a flexbox with 4 columns. Is it possible with pure css to restart nth child at beginning row? I want to get this backgrounds

▓░▓░

░▓░▓

▓░▓░

when responsive resizing it should stay the rotation

▓░▓

░▓░

▓░▓

░▓░

I tried nth-child but at 4 columns the next row starts with dark again.

$( document ).ready(function(){for (i = 1; i < 12; i++){$( "#parent .child:first-child" ).clone().appendTo( "#parent" );
}});
#wrapper {
  width: 70%;
  margin: 0 auto;
}

#parent {
  display: flex;
  flex-flow: row wrap;
  align-items: stretch;
  justify-content: flex-start;
}

#parent > .child {
  margin: 10px;
  flex-basis: calc( 100% / 4 );     
  max-width: calc( 100% / 4 - 20px ); 
  width: calc( 100% / 4 - 20px ); 
  background: rgba(0,0,255,0.2);
  padding: 10px;
  box-sizing: border-box;
}

#parent > .child:nth-child(2n) {
  background: rgba(0,255,255,0.2);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="wrapper">
  <div id="parent">
    <div class="child">
      <h4>Lorem Ipsum</h4>
      <span>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy</span>
    </div>
</div>

1 Answers

Simplifying the example I mentioned earlier by Damon -> https://dev.to/thedamon/maintaining-a-pattern-across-a-responsive-grid-4j2b

no JS needed, the key is that grid-auto-flow:dense property which reflows items, then you just select the first item of every 2nd row with nth-child, and shift that to the end of the row with grid-column, but you don't need to do that for a grid with an odd number of columns, just even. If that makes sense.

$( document ).ready(function(){for (i = 1; i < 12; i++){$( "#parent .child:first-child" ).clone().appendTo( "#parent" );
}});
#wrapper {
  width: 70%;
  margin: 0 auto;
}

#parent {
  display: grid;
  grid-gap: 20px;
  grid-template-columns: repeat(4, auto);
  grid-auto-flow: dense;
  /*display: flex;
  flex-flow: row wrap
  align-items: stretch;
  justify-content: flex-start;*/
}

#parent > .child {
  /*margin: 10px;
  flex-basis: calc( 100% / 4 );     
  max-width: calc( 100% / 4 - 20px ); 
  width: calc( 100% / 4 - 20px ); */
  background: rgba(0,0,255,0.2);
  padding: 10px;
  box-sizing: border-box;
}

#parent > .child:nth-child(2n) {
  background: rgba(0,255,255,0.2);
}

/*full-width breakpoint */
@media screen and (min-width:1001px) {
    .child:nth-child(8n + 5) {
        grid-column: 4;
    }
}


/*smaller screen breakpoint */
@media screen and (max-width:1000px) {
    #parent {
        grid-template-columns: repeat(3, auto);
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="wrapper">
  <div id="parent">
    <div class="child">
      <h4>Lorem Ipsum</h4>
      <span>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy</span>
    </div>
</div>

Related