Is it possible to have a child element behind his

2019-01-14 22:08发布

I would like to know if it possible to have a child element behind his parent element with z-index.

I would like to use the parent div as transparent color layer on top of his content.

5条回答
【Aperson】
2楼-- · 2019-01-14 22:42

Why not? Sure you can, and it's easy:

  1. give a non-static position to your desired elements;
  2. set z-index of child to -1;
  3. create a stacking context on the main container (by setting on it a z-index, opacity, transforms or whatelse generates a composite layer).

.container {
    position: absolute;
    z-index: 0; /* or eg. opacity: 0.99;*/
  
    background-color: blue;
    color: lightblue;
    width: 100%;
    height: 100%;
    text-align: center;
}

.parent {
    position: relative;
  
    background-color: rgba(100, 255, 150, 0.75);
    color: green;
    width: 50%;
    height: 30%;
    top: 30%;
    left: 20%;
}

.child {
    position: absolute;
    z-index: -1;
  
    background-color: orange;
    color: yellow;
    width: 100%;
    height: 100%;
    top: -50%;
    left: 20%;
}
<div class="container">
    <span>container</span>
    <div class="parent">
        <span>parent</span>
        <div class="child">
            <span>child</span>
        </div>
    </div>
</div>

(if the parent is used as a transparent layer, be sure to use a background-image or rgba background-color: children inherit the opacity of the parent)

查看更多
干净又极端
3楼-- · 2019-01-14 22:44

The short answer is Yes ;) There is an excellent article here that describes how you can use the stacking order of elements to allow the z-index to be negative in order to place an element behind it's parent.

http://philipwalton.com/articles/what-no-one-told-you-about-z-index/

查看更多
手持菜刀,她持情操
4楼-- · 2019-01-14 22:58

You could just do it the other way and use the child as the overlay like this

HTML

<div id="stuff"><div class="overlay"></div>
    <p>
    Cras venenatis ornare tincidunt. Nam laoreet ante sed nibh pretium nec gravida turpis dapibus. Curabitur lobortis; lacus sit amet rutrum aliquet, est massa feugiat lectus, bibendum eleifend velit metus vitae dolor! Duis vulputate mi vitae quam fermentum pharetra.
    </p>
</div>

CSS

#stuff{
    position:relative;
    }

.overlay{
    width:100%;
    height:100%;
    position:absolute;
    top:0;
    left:0;
    background:#ACA;
    opacity:0.4;
    }
查看更多
爱情/是我丢掉的垃圾
5楼-- · 2019-01-14 23:01

Not possible, because each positioned element creates a stacking context.

Explanation 1, Explanation 2

查看更多
干净又极端
6楼-- · 2019-01-14 23:05

While this wouldn't necessarily work in all browsers (especially older ones), the following has worked for me in the past:

#child {
  position: relative;
  z-index: -1;
  ...
}

I'm really only suggesting this as a last resort and would still prefer to use any technique other than this, although it might be ideal in your scenario.

查看更多
登录 后发表回答