Z-Index结合位置:固定和过渡(CSS)

时间:2015-07-10 15:11:26

标签: css position z-index transition

我正在设置新的投资组合网站并使用Onepage Scroll Plugin by Pete R.

我添加了修复导航栏,现在希望幻灯片中的元素与此导航重叠。这是codepen的代码示例:

http://codepen.io/terrorpixel/pen/BNxYxq

HTML

<nav></nav>
<div class="container">
  <div>Bring me to the front!</div>
</div>

CSS

nav {
    height: 82px;
    left: 0;
    position: fixed;
    top: 0;
    -webkit-transition: background 1.15s ease-in-out 0s;
    -moz-transition: background 1.15s ease-in-out 0s;
    transition: background 1.15s ease-in-out 0s;
    width: 100%;
    z-index: 2;  
    background:rgba(0,255,0,.85);
}

.container {
    background:blue;
    position: relative;
    -webkit-transform: translate3d(0px, -1%, 0px);
    -moz-transform: translate3d(0px, -1%, 0px);
    transform: translate3d(0px, -1%, 0px);
    -webkit-transition: all 2s ease 0s;
    -moz-transition: all 2ms ease 0s;
    transition: all 2ms ease 0s;
    height: 5000px; 
    z-index:1;
    width: 70%;
    margin: 0 auto;
}

.container div {
    padding: 250px 100px;
    z-index:10;
    position:absolute;
    right:0; 
    top:0;
    background:red;
}

我试着将红色框放到前面。我认为失败属于我在不同的堆叠环境中使用z-index的事实。 .container里面也没有工作..实际上是否有可能意识到:/?

1 个答案:

答案 0 :(得分:1)

您需要将.container div移到.container之外。 将定位元素放置在定位元素中时,子元素将启动新的堆叠顺序,但它会在父元素值的上下文中启动。因此,即使您为z-index为2的父项的子项指定了z-index值10000,也就像子项的z-index为2.10000一样。

这个例子粗略但你明白了:

nav {
  height: 82px;
  left: 0;
  right: 0;
  position: fixed;
  top: 0;
  -webkit-transition: background 1.15s ease-in-out 0s;
  -moz-transition: background 1.15s ease-in-out 0s;
  transition: background 1.15s ease-in-out 0s;
  z-index: 2;
  background: rgba(0, 255, 0, .85);
}
.container {
  background: blue;
  position: relative;
  -webkit-transform: translate3d(0px, -1%, 0px);
  -moz-transform: translate3d(0px, -1%, 0px);
  transform: translate3d(0px, -1%, 0px);
  -webkit-transition: all 2s ease 0s;
  -moz-transition: all 2ms ease 0s;
  transition: all 2ms ease 0s;
  height: 5000px;
  z-index: 1;
  width: 70%;
  margin: 0 auto;
}
.front {
  z-index: 3;
  position: absolute;
  right: 15%; /* half of 30% (the left over of 70% container width) */
  top: 82px;
  background: red;
}
<nav></nav>
<div class="container">
</div>
<div class="front">Bring me to the front!</div>
</div>