在后面隐藏div

时间:2018-12-05 21:14:20

标签: html css fixed behind

我尝试做一个简单的思考,但是我被困住了。 我有一个固定位置的div“滚动”。滚动页面时,我希望div“滚动”位于下面所有其他div的后面。

我举了一个例子:exemple jsfiddle

.scrolling{
  top: 230px;
  background-color:lightblue;
  margin:auto;
  width:100%;
  text-align:center;
  position:fixed;
}

谢谢您的帮助

4 个答案:

答案 0 :(得分:3)

可与z-index一起使用。但是要使z-index有效,它必须为position: absoluteposition:fixedposition:relative

.top{
  width:auto;
  background-attachment: fixed; 
  height:300px;  
    background-image: linear-gradient(pink, green);
}
.scrolling{
  top: 230px;
  background-color:lightblue;
  margin:auto;
  width:100%;
  text-align:center;
  position:fixed;
  z-index:4;
}
<div class="top">
  <div>
    Hello
  </div>
  <div>
    Hello
  </div>
</div>
<div class="scrolling">
  SCROLL
  <br>
  I want to stay behind the div grey
</div>

<div style="width:auto; height:50px; background-color:grey;position:relative;z-index:5">

</div>
  
<div style="width:auto; height:350px; background-color:grey;position:relative;z-index:5">
  I want to be in displayed in front
</div>

答案 1 :(得分:0)

请确保您要在此处使用(z索引)。

我在下面更新了您的小提琴。 Z索引使您可以从前到后定位。

<div class="top">
  <div>
    Hello
  </div>
  <div>
    Hello
  </div>
</div>
<div class="scrolling">
  SCROLL
  <br>
  I want to stay behind the div grey
</div>


<div class="front" style="width:auto; height:350px; background-color:grey;">
  I want to be in displayed in front
</div>

.top{
  width:auto;
  background-attachment: fixed; 
  height:300px;  
  background-image: linear-gradient(pink, green);
  z-index: 0;
}
.scrolling{
  top: 230px;
  background-color:lightblue;
  margin:auto;
  width:100%;
  text-align:center;
  position:fixed;
  z-index: 0;
}
.front{
  z-index: 1;
  position: relative;
}

答案 2 :(得分:0)

要回答您的问题,您需要了解z-index之类的概念和/或堆叠顺序的工作方式。有很多很棒的文章会解释z-index,但是我特别喜欢的是What no one told you about z-index

上面引用的文章的摘录:

  

将position属性引入混合时,所有已定位元素(及其子元素)都显示在任何未定位元素的前面。 (要说一个元素是“定位的”,则表示该元素的位置值不是静态值,例如相对值,绝对值等)。

有趣的是,有一个CSS3属性可以执行类似的操作。您可以使用transform解决您的问题,而无需显式应用z-index。

例如,如果我们将transform: translateX(0)应用于您的JSFiddle,您会看到灰色div现在位于文本上方。这是更新的小提琴:

https://jsfiddle.net/gh94Lbad/

<div style="width:auto; height:50px; background-color:grey; transform: translateX(0)"></div>
<div style="width:auto; height:350px; background-color:grey;transform: translateX(0)">I want to be in displayed in front</div>

规范中说明了transform有效(通过修改堆栈上下文)的原因:

  

对于其布局由CSS box模型控制的元素,transform属性的任何值(无值)都会导致创建堆栈上下文。实现必须在其父堆栈上下文中以其堆叠顺序(如果该元素是具有z-index的定位元素:0)绘制其创建的层。如果已定位具有转换的元素,则z-index属性如[CSS2]中所述适用,但将auto视为0,因为始终会创建新的堆栈上下文。

编辑:作为pointed out by @TemaniAfif,最好通过解释元素的paint order来解释其工作原理:

  

为此,您需要考虑绘画顺序(w3.org/TR/css-position-3/#painting-order),在该顺序中您发现转换后的元素随后被绘画,因此位于上方。 (在步骤(8)中)

答案 3 :(得分:0)

您需要对要显示的元素使用更多的z-index,对元素“后置”使用更少的z-index。

相关问题