CSS如何为表格行添加内部inset投影效果?

3

请参考我相关的但不同的问题:如何为表格行添加CSS阴影?

Here is my HTML code:

<style>
.yellow{
    background-color: yellow;
}
td{
    width:40px;
}
tr:first-child {
    box-shadow: inset 1px 1px 5px 5px #d99292;
}
</style>
<table>
    <tr>
        <td class=yellow>1</td>
        <td>2</td>
    </tr>
    <tr>
        <td>3</td>
        <td class=yellow>4</td>
    </tr>
</table>

The goal is to have a inset drop shadow in the first row. The problem is that the background color of cell 1 is obscuring it.

我的问题是:如何使内嵌下拉框显示在单元格1的背景上方?
3个回答

2
使用伪元素在阴影后面创建并着色表格单元格:

table {
  position:relative;
  z-index:-1;
}

.yellow {
  position:relative;
}
.yellow::before {
  content:"";
  position:absolute;
  z-index:-1;
  top:0;
  left:0;
  right:0;
  bottom:0;
  background:yellow;
}

td {
  width: 40px;
}

tr:first-child {
  box-shadow: inset 1px 1px 5px 5px #d99292;
}
<table>
  <tr>
    <td class=yellow>1</td>
    <td>2</td>
  </tr>
  <tr>
    <td>3</td>
    <td class=yellow>4</td>
  </tr>
</table>


2

你也可以尝试使用mix-blend-mode

mix-blend-mode CSS属性设置元素内容与父元素和背景内容的混合方式。

.yellow{
    background-color: yellow;
    mix-blend-mode:multiply
}
td{
    width:40px;
}
tr:first-child {
    box-shadow: inset 1px 1px 5px 5px #d99292;
 /*optionnal :
    background:white ; 
  to avoid .yellow mixing eventually with body, or else background */
}
<table>
    <tr>
        <td class=yellow>1</td>
        <td>2</td>
    </tr>
    <tr>
        <td>3</td>
        <td class=yellow>4</td>
    </tr>
</table>


谢谢!这是最简单的答案,而且在我的更复杂的项目中也非常有效。 - yigal

1

我这里有一个解决方法。

添加一个绝对空的 tr 到顶部。

.yellow{
    background-color: yellow;
}
td{
    width:40px;
}
tr:first-child {
    position: absolute;
    box-shadow: inset 1px 1px 5px 5px #d99292;
}
<table>
  <tr>
    <td>&nbsp;</td>
    <td></td>
  </tr>
  <tr>
    <td class=yellow>1</td>
    <td>2</td>
  </tr>
  <tr>
    <td>3</td>
    <td class=yellow>4</td>
  </tr>
</table>


1
将tr的display属性设置为flex会破坏表格布局(https://jsfiddle.net/9gjcm2rz/)。 - Temani Afif
@TemaniAfif 感谢您指出这一点。虽然在此情况下它可以工作,因为td设置了宽度,但我将更新答案以删除该解决方案。 - huan feng

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接