是否可以在几行 table 上设置一个线性渐变背景?

Is it possible to set one linear gradient background on several table rows?

我需要为 table 中的连续 3 行设置单个线性渐变背景:

<table>
  <tbody>
    <tr><td>1</td></tr>
    <!-- background starts here -->
    <tr class="bg"><td>2</td></tr>
    <tr class="bg"><td>3</td></tr>
    <tr class="bg"><td>4</td></tr>
    <!-- background ends here -->
    <tr><td>4</td></tr>
  </tbody>
</table>

我现在拥有的是每行一个渐变:http://jsfiddle.net/orkLLbpz/。有什么想法可以从这里开始吗?

请注意 table 中的所有行都在 tbody 元素中,因此我不能使用另一个 tbody 来对这些行进行分组。

我认为这不可能,我在一个项目中也有同样的需求。

我做了什么:使用这样的 css 技巧

.bg1 {
  background: linear-gradient(to bottom, #FFF 0%, #f7f6f6 100%) repeat scroll 0% 0% transparent;
}
.bg2 {
  background: linear-gradient(to bottom, #f7f6f6 0%, #f4f4f4 100%) repeat scroll 0% 0% transparent;
}
.bg3 {
  background: linear-gradient(to bottom, #f4f4f4 0%, #EEE 100%) repeat scroll 0% 0% transparent;
}

Updated Jsfiddle

这不是一个正确的答案,但可能适合你。

不幸的是,如果不将它们分组在自己的 tbody 中,这是不可能的。您可以将渐变分成 3 部分,并将每个部分作为背景添加到第一行、第二行和第三行,每个部分都与其他部分混合,但是每个行的高度可能不同,您最终可能会得到看起来像 'higher' 比其他人.

另一种选择是使用绝对定位元素在适当的行后面添加线性渐变背景。

在这种情况下,我们必须知道 first/last 行的高度才能在 top/bottom 偏移量上设置适当的值。

table {
    width: 100%;
    position: relative;
    border: 1px solid; /* Just for demo */
    border-spacing: 0; /* Just for demo */
}

table:before {
    content: "";
    position: absolute;
    top: 1.2em;
    bottom: 1.2em;
    left: 0;
    right: 0;
    background: linear-gradient(to bottom, #FFF 0%, #EEE 100%) repeat scroll 0% 0% transparent;
    z-index: -1;
    
    outline: 1px dashed red; /* Just for demo */
}
<table>
    <tbody>
        <tr><td>1</td></tr>
        <!-- background starts here -->
        <tr class="bg"><td>2</td></tr>
        <tr class="bg"><td>3</td></tr>
        <tr class="bg"><td>4</td></tr>
        <!-- background ends here -->
        <tr><td>4</td></tr>
    </tbody>
</table>

因此,为了让这个正确,您想要 运行 一种颜色并在所有行中将其淡入另一种颜色?

我能想到的唯一方法是使用 SCSS 函数。

@mixin shades-of-color ( $count, $startcolor ) {
  @for $i from 0 through $count {
   /* Adds slight amount of black to each varient of your $startcolor */
    $background-color: mix(black, $startcolor, $i + $i);

    .bg:nth-of-type(#{$i}) {
      background-color: $background-color;

      /* Allows your hover to be the same shade */
      &:hover {
        background-color: mix(white, $background-color, 20);
      }
    }
}    
}

@include shades-of-color(20,#2d89ef);
/*The `20` here is from the number of times you want it to repeat*/
/* Change the #2d89ef */ to your color of choice.

SCSS 是解决此问题的唯一合理方法,因为您可以 运行 它作为一个函数,否则您将需要在每一行上 运行 一个 class 来定义它。

如果您不能在此项目中使用 SCSS,我们深表歉意,但除非您 class 输出每一行,否则这似乎是唯一可行的解​​决方案。如果你不明白这个mixin,我可以更深入地解释它。

编辑:这是一个 codepen,您可以看到每个 table 行通过为先前的颜色添加阴影而变得越来越暗。

我相信更简洁的做法是在整个 table 上设置渐变,并将背景颜色设置为第一个和最后一个