如何使用z-index对盒子阴影进行分层?

mpe*_*pen 9 css css3

codepen

HTML

<div id="a">
  <div id="b">bbb</div>
  <div id="c">
    <ul>
      <li>a</li>
      <li class="current">b</li>
      <li>c</li>
      <li>d</li>
    </ul>
  </div>
</div>
<div id="d">dddd
</div>
Run Code Online (Sandbox Code Playgroud)

CSS

#b {
  background: orange;
  box-shadow: 0 0 10px black;
  z-index: 2;
  position: relative;
}

#c {
  background: red;
  z-index: 1;
  position: relative;
}

ul {
  list-style: none;
  margin: 0;
  padding: 0;
  z-index: 1;
  position: relative;
}
li {
  display: inline-block;
  padding: 2px 5px;
}

.current {
  background-color: orange;
  z-index: 3;
  position: relative;
}

#d {
  box-shadow: 0 0 10px black;
  z-index: 2;
}
Run Code Online (Sandbox Code Playgroud)

看看代码笔.我的层数或多或少都是我想要的,除了我希望"b"标签位于由上面的橙色div引起的盒子阴影之上.

详细说明,橙色#bdiv应该在红色#cdiv 上投射阴影,.current标签应该与橙色#bdiv 齐平(没有阴影),并且#d根本应该投射阴影#c.

问题是,z-index开启.current似乎不起作用.

小智 28

如果您正在使用z-index,请确保该元素具有已定义的位置属性,否则将无效.无论您在css中使用z-index,都要定义该元素的位置.(绝对,相对,继承...)

  • 很容易错过“位置:相对”,这个答案拯救了我的一天 (2认同)
  • 这个答案与这个问题不正确/不相关;OP 已经向所有相关元素添加了“position”值。 (2认同)

Arb*_*bel 10

演示: http ://codepen.io/anon/pen/vLgKC

有关更多信息z-index和堆叠上下文和优先级,请在此处查看我的答案.

以上,与组合insetbox-shadow

插页

如果未指定(默认),则假定阴影为阴影(就好像该框被提升到内容之上).inset关键字的存在将阴影更改为框架内的阴影(就像在框内按下内容一样).在边框内部(甚至是透明的)绘制插入阴影,在背景上方,但在内容下方.

还有一个 negative spread

传播半径

这是第四个值.正值将导致阴影扩大并变大,负值将导致阴影缩小.如果未指定,则为0(阴影将与元素的大小相同).

(两个在这里)

会给你你想要的效果.

因此,您需要更改阴影应用于元素的位置.

所以最终的CSS:

#b {
  background: orange;
  z-index: 2;
  position: relative;
}

#c {
  background: red;
  -webkit-box-shadow: inset 0 10px 10px -10px black;
  -moz-box-shadow: inset 0 10px 10px -10px black;
  box-shadow: inset 0 10px 10px -10px black;
  z-index: 1;
  position: relative;
}

ul {
  list-style: none;
  margin: 0;
  padding: 0;
  z-index: 1;
  position: relative;
}
li {
  display: inline-block;
  padding: 2px 5px;
}

.current {
  background-color: orange;
  z-index: 3;
  position: relative;
}

#d {
  box-shadow: 0 0 10px black;
  z-index: 2;
}
Run Code Online (Sandbox Code Playgroud)

  • 使用插入阴影创造另一个元素在当前元素上投下阴影的错觉是一个非常有用的 CSS 技巧!非常适合实现正确阴影外观的 DOM 顺序对于 Tab 键顺序等错误的情况。 (2认同)