Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS flex box alternate row colors

Tags:

css

flexbox

When using tables, it is easy to alternate colors in table rows using the nth child selectors (https://stackoverflow.com/a/3084318/1385857). Is there a comparable way to do so when using the flexbox layout. I have the following (from https://philipwalton.github.io/solved-by-flexbox/demos/grids/):

<div class="Grid">
  <div class="Grid-cell"></div>
  [more divs]
  <div class="Grid-cell"></div>
</div>

.Grid
{
  display: flex;
  flex-wrap: wrap;
}

.Grid-cell
{
  flex: 1;
}

Is it possible to alternate row colors in this scenario. To clarify, there are no real rows, only the virtual rows created by flex box due to wrapping.

like image 907
Manish Avatar asked Nov 09 '22 12:11

Manish


1 Answers

A bit late but it might help others. Here is a working solution I've just come up with. It uses the linear-gradient CSS function.

The only downside is that it requires your cells to have a fixed height.

/* $cell_height: 80px */

.grid {
  display: flex;
  flex-flow: row wrap;

  /* this is where the magic is */
  background-image: linear-gradient(180deg, red 50%, green 50%);
  background-repeat: repeat;
  background-size: 100px 160px; /* width is not relevant, but height must be 2*$cell_height */
}

.grid-cell {
  height: 80px; /* $cell_height */
  
  /* this is just to have a responsive display for the demo */
  width: 25%;
  min-width: 250px;
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}
<div class="grid">
  <div class="grid-cell">1</div>
  <div class="grid-cell">2</div>
  <div class="grid-cell">3</div>
  <div class="grid-cell">4</div>
  <div class="grid-cell">5</div>
  <div class="grid-cell">6</div>
  <div class="grid-cell">7</div>
  <div class="grid-cell">8</div>
  <div class="grid-cell">9</div>
  <div class="grid-cell">10</div>
  <div class="grid-cell">11</div>
  <div class="grid-cell">12</div>
  <div class="grid-cell">13</div>
  <div class="grid-cell">14</div>
</div>
like image 92
julienc Avatar answered Nov 15 '22 13:11

julienc