Is there a way to snake/queue the flow of items in a CSS Grid?

Viewed 109

Default behavior:

|A|B|C|D| |E|F|G|H| |I|J|K|L|

Desired behavior:

|A|B|C|D| |H|G|F|E| |I|J|K|L|

I've looked into the grid-auto-flow property as well as the direction property but there seems to be no workaround without resorting to javascript. Is there a way to achieve this with CSS?

1 Answers

You can use flex properties and nth-child selector

<div class="snakeContainer">
  <div>
    <span>A</span>
    <span>B</span>
    <span>C</span>
    <span>D</span>
  </div>
  <div>
    <span>E</span>
    <span>F</span>
    <span>G</span>
    <span>H</span>
  </div>
  <div>
    <span>I</span>
    <span>J</span>
    <span>K</span>
    <span>L</span>
  </div>
</div>

<style>
.snakeContainer div:nth-child(even){
  display: flex;
  flex-direction: row-reverse;
  justify-content: flex-end;
}

.snakeContainer div:nth-child(odd){
  display: flex;
}
</style>

Related