简体   繁体   中英

Unexpected z-index stacking behavior

Basically, I am trying to put overlap corners behind the #page_container on my site, so that it looks like the image is overlapping the page.

Live example: http://jsfiddle.net/xBwQp/15/

HTML :

<div id="page_container">
    <div id="banner_wrapper">
        <img id="banner_image" src="http://placehold.it/350x150" />
        <div class="triangle-l"></div>
        <div class="triangle-r"></div>        
    </div>
</div>

CSS :

#page_container {
    background: red;
    width: 400px;
    position: relative;
    z-index: 10;
}

#banner_wrapper {
  position: relative;
}

#banner_image {
  position: relative;
}

.triangle-l {
  border-color: transparent green transparent transparent;
  border-style: solid;
  border-width: 15px;
  height: 0px;
  width: 0px;
  position: absolute;
  right: 0px;
  top: 0px;
  z-index: 5;
}

.triangle-r {
  border-color: transparent transparent transparent blue;
  border-style: solid;
  border-width: 15px;
  height: 0px;
  width: 0px;
  position: absolute;
  right: 0px;
  top: 0px;
  z-index: 5;
}

You can see that the triangles, .triangle-l and .triangle-r , clearly have a lower z-index:5 than the #page_container z-index:10 but they still appear above the #page_container .

I have been able to accomplish my desired result by setting .triangle-l and .triangle-r to z-index:-1 however this only works in FF, Opera, and Webkit. No IE support.

I believe it has to do with the stacking context. However, I am unsure how to accomplish the desired result with cross-browser compatibility.

You are absolutely right - it is about the stacking context.

Whenever you put z-index on an element you create a new context, so because the triangles are descendants of the #page_container they are going to belong to the stacking context of the #page_container and no matter what z-index number you choose for the triangles, they only have meaning inside this context, and you will not be able to move them backwards behind this container.

Read in detail here: https://developer.mozilla.org/en/CSS/Understanding_z-index/The_stacking_context

Possible solutions are;

  • move the elements out of the container in the html structure (and then position them where you want with css)
  • remove the z-index from the container and set the triangles to z-index -1 to move them beneath the document itself

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM