CSS flex box交替行颜色

时间:2016-07-11 11:45:19

标签: css flexbox

使用表时,使用第n个子选择器(https://stackoverflow.com/a/3084318/1385857)可以很容易地在表行中交替显示颜色。使用flexbox布局时是否有类似的方法可以这样做。我有以下内容(来自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;
}

在这种情况下是否可以替换行颜色。为了澄清,没有真正的行,只有由于包装而由flex框创建的虚拟行。

2 个答案:

答案 0 :(得分:1)

有点晚了,但可能会对其他人有所帮助。这是我刚想出的可行解决方案。 它使用linear-gradient CSS函数。

唯一的缺点是它要求您的单元格具有固定的高度。

/* $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>

答案 1 :(得分:-2)

您可以使用与nth-child(2n + 1,偶数,奇数)相同的技术,或任何您想要的技术。

元素的显示不会干扰这里。

&#13;
&#13;
.Grid {
  display: flex;
  flex-wrap: wrap;
}
.Grid-row {
  flex: 1;
}
.Grid-cell:nth-child(2n+1) {
  background: pink;
}
&#13;
<div class="Grid">
  <div class="Grid-row">
    <div class="Grid-cell">Grid-cell 1</div>
    <div class="Grid-cell">Grid-cell 2</div>
    <div class="Grid-cell">Grid-cell 3</div>
    <div class="Grid-cell">Grid-cell 4</div>
    <div class="Grid-cell">Grid-cell 5</div>
    <div class="Grid-cell">Grid-cell 6</div>
    <div class="Grid-cell">Grid-cell 7</div>
  </div>
  <div class="Grid-row">
    <div class="Grid-cell">Grid-cell 1</div>
    <div class="Grid-cell">Grid-cell 2</div>
    <div class="Grid-cell">Grid-cell 3</div>
    <div class="Grid-cell">Grid-cell 4</div>
    <div class="Grid-cell">Grid-cell 5</div>
    <div class="Grid-cell">Grid-cell 6</div>
    <div class="Grid-cell">Grid-cell 7</div>
  </div>
</div>
&#13;
&#13;
&#13;