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

时间:2015-06-17 13:07:57

标签: html css css-tables

我需要为表中的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/。任何想法如何从这里开始?

请注意,表格中的所有行都在tbody元素中,因此我无法使用其他tbody对这些行进行分组。

5 个答案:

答案 0 :(得分:2)

我不认为这是可能的,我在项目中也有同样的要求。

我做了什么:使用像这样的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

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

答案 1 :(得分:2)

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

在这种情况下,我们必须知道第一行/最后一行的高度,以便在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>

答案 2 :(得分:0)

不幸的是,如果没有将它们分组到自己的tbody中,那是不可能的。您可以将渐变分为3个部分,并将每个渐变作为背景添加到第1行,第2行和第3行,每个行与其他行混合,但每行高度可能不同,您最终可能会看到渐变的区域&# 39;高级&#39;比其他人。

答案 3 :(得分:0)

为了使这一点正确,你想运行1种颜色并将其淡入所有行中的另一种颜色?

我能想到的唯一方法就是使用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是唯一合理的方法,因为你可以将它作为一个函数运行,否则你需要在每一行上运行一个类来定义它。

如果您不能在此项目中使用SCSS,请道歉,但除非您对每一行进行分类,否则这似乎是唯一可行的解​​决方案。如果你不理解这个mixin,我可以更深入地解释它。

编辑:这是 codepen ,您可以看到每个表格行通过为前一种颜色添加阴影来变暗和变暗。

答案 4 :(得分:0)

我相信更清洁的举动是在整个桌子上设置渐变并将背景颜色设置为第一个和最后一个

相关问题