Inset box-shadow beneath content

2019-02-16 04:08发布

I don't understand why, but an inset box shadow is beneath my content.

Here's an example:

div {
   box-shadow:inset 0 0 10px black;
   height:300px;
   color:red;
}
<div>
   a
</div>

http://jsfiddle.net/MAckM/

You see the a is on top of the box shadow.

How can I get the box shadow to be on top of the a?

标签: css z-index css3
2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-02-16 04:45

You need to make a new element inside the div, with absolute positioning and height and width of 100%, then give that element the box shadow.

HTML:

<div>
    <div></div>
    a
</div>​

CSS:

div {
    height:300px;
    color:red;
    position:relative;
}

div div {
    box-shadow:inset 0 0 10px black;
    position:absolute;
    top:0;
    left:0;
    width:100%;
    height:100%;
}​

Here is a JSFiddle.

Edit:

Alternatively, you can use a pseudo element:

HTML:

<div>
    a
</div>​

CSS:

div {
    height:300px;
    color:red;
    position:relative;
}

div:before {
    content:'';
    display:block;
    box-shadow:inset 0 0 10px black;
    position:absolute;
    top:0;
    left:0;
    width:100%;
    height:100%;
}​

JSFiddle.

查看更多
迷人小祖宗
3楼-- · 2019-02-16 04:56

This answer offers the most straightforward solution via a minimal example and addresses the issue of scrolling.

Unfortunately there is no way to avoid an extra wrapping div (due to box-shadow layering).

.container {
  position: relative;
}

.container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  box-shadow: inset 0 0 9px 3px yellow;
  pointer-events: none;
}

.items {
  height: 100px;
  overflow: scroll;
}
<div class="container">
  <div class="items">
    <div class="item">One</div>
    <div class="item">Two</div>
    <div class="item">Three</div>
    <div class="item">Four</div>
    <div class="item">Five</div>
    <div class="item">Six</div>
    <div class="item">Seven</div>
    <div class="item">Eight</div>
    <div class="item">Nine</div>
    <div class="item">Ten</div>
    <div class="item">Eleven</div>
    <div class="item">Twelve</div>
  </div>
</div>

查看更多
登录 后发表回答