具有绝对位置的div被隐藏

时间:2020-03-07 07:22:53

标签: html css

这是我的简单代码。

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.one {
  background: yellow;
  height: 100px;
  position: absolute;
}

.two {
  background: blue;
  height: 400px;
  position: absolute;
}

.three {
  background: red;
  height: 300px;
}
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>

这就是outputJSFiddle中的样子。现在,类1和2具有绝对位置,因此它们不再属于常规文档流。因此,红色的三班级转移到顶部。我明白那个。但是第一班(黄色)和第二班(蓝色)怎么了?我认为第三节课应该转移到顶部,并与第一节课和第二节课重叠。那么,这里发生了什么?

3 个答案:

答案 0 :(得分:2)

要点是您提到了absolute div的高度,但从未提及宽度。因此absolute div不会消失,但由于宽度为零而不会显示。

我们应该牢记,当您将任何元素设置为absolute时,应该设置widthheight,在其中放置内容或提及left {{1 }}坐标。

请参见here

right
* {
  margin : 0;
  padding: 0 ;
  box-sizing: border-box;
}

.one {
  background: yellow ;
  width: 100px;
  height: 100px ;
  position: absolute ;
}

.two {
  background: blue;
  height: 400px ;
  position: absolute ;
  left: 25%;
  right: 25%;
}

.three {
  background: red ;
  height: 300px ;
}

答案 1 :(得分:0)

具有以下位置的元素:绝对;相对于最近定位的祖先定位(而不是相对于视口定位,如固定)。如果要显示所有三个div,可以尝试以下操作:

.one {
  background: yellow ;
  height: 100px ;
}

.two {
  background: blue ;
  height: 400px ;
}

您只需要除去position:absolute,因为它就像固定位置一样工作。希望对您有所帮助。如有任何疑问,请随时讨论!

答案 2 :(得分:0)

如果要查看隐藏的div,则需要添加z-index属性。

.one {
  background: yellow ;
  width: 100px;
  height: 100px ;
  position: absolute ;
  /* Increase numbers as your need */
  z-index: 1;
}

.two {
  background: blue;
  height: 400px ;
  position: absolute ;
  left: 25%;
  right: 25%;
  /* Increase numbers as your need */
  z-index: 2;
}

.three {
  background: red ;
  height: 300px ;
}