如何使box-shadow出现在div上方?

27

这里有一个示例,展示了我想要实现的效果。

上方的 divbox-shadow 不会出现在下面的 div 上方。据我所知,我需要设置 z-index 使其出现在上方,并且只对具有 position: relative; 属性的元素有效,但它仍未出现。

我做错了什么?

#top {
    width: 100%;
    height: 100px;
    box-shadow: 3px 3px 3px #333;
    background-color: blue;
}

#middle {
    width: 100%;
    height: 200px;
    z-index: 0;
    position: relative;
    background-color: orange;
}

#innerMiddle {
    width: 200px;
    height: 200px;
    margin: 0 auto;
    background-color: green;
}
<div id="top">
</div>

<div id="middle">
    <div id="innerMiddle">
    </div>
</div>

3个回答

64

你希望让 #top 和它的阴影显示在最上面,所以将 position: relative 给予它,而不是给予 #middle。不需要添加 z-index: 0

http://jsfiddle.net/thirtydot/QqME6/1/

#top {
    width: 100%;
    height: 100px;
    box-shadow: 3px 3px 3px #333;
    background-color: blue;
    
    position: relative;
}

#middle {
    width: 100%;
    height: 200px;
    background-color: orange;
}

#innerMiddle {
    width: 200px;
    height: 200px;
    margin: 0 auto;
    background-color: green;
}
<div id="top">
</div>

<div id="middle">
    <div id="innerMiddle">
    </div>
</div>


11
请提供需要翻译的具体内容。
#top {
    width: 100%;
    height: 100px;
    box-shadow: 3px 3px 3px #333;
    background-color: blue;
    position:relative;
    z-index:1;
}

#middle {
    width: 100%;
    height: 200px;
    z-index: 0;
    position: relative;
    background-color: orange;
}
<div id="top">
</div>

<div id="middle">
    <div id="innerMiddle">
    </div>
</div>


0

在上层div中使用position: relative,而不是在下层div中使用

#top {
  width: 100%;
  height: 100px;
  box-shadow: 3px 3px 3px #333;
  background-color: blue;
  position: relative;
}

#middle {
  width: 100%;
  height: 200px;
  z-index: 0;
  /* position: relative; */
  background-color: orange;
}

#innerMiddle {
  width: 200px;
  height: 200px;
  margin: 0 auto;
  background-color: green;
}
    <div id="top"></div>
    <div id="middle">
      <div id="innerMiddle"></div>
    </div>


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