使DIV全屏并且像位置相对一样

时间:2016-10-03 12:13:42

标签: css css-position

我想要一个div元素来填满整个屏幕。所以我有以下几项:

<div style="background:black;position:absolute;top:0;left:0;right:0;bottom:0;"></div>
<div>Hello</div>
<div>World</div>

我遇到的问题是Hello World div出现在全屏div之上。我希望Hello World div出现在全屏div之后,所以你必须滚动到它。

基本上,我希望全屏幕div的行为就像它相对定位一样。我不想使用javascript来硬编码Hello World div的起始位置。

是否有一种简单的方法可以实现我想要的CSS?

由于

3 个答案:

答案 0 :(得分:3)

为了让第一个<div>全屏,您只需要利用vh长度单位,而不是绝对定位:

&#13;
&#13;
/* Removing padding and margin from
   the specified elements: */
html,
body {
  margin: 0;
  padding: 0;
  border-width: 0;
}
/* a <div> is already 100% wide,
   so we specify only the height,
   and ensure that any lengths
   are calculated to include
   border-width, padding and margin
   using the box-sizing property: */
.fullpage {
  height: 100vh;
  box-sizing: border-box;
}
/* purely so that there is something
   to see easily, irrelevant to the
   demo: */
div:nth-child(odd) {
  background-color: #f90;
}
div {
  min-height: 2em;
  margin: 0;
  padding: 0;
}
&#13;
<div class="fullpage"></div>
<div>Hello</div>
<div>World</div>
&#13;
&#13;
&#13;

JS Fiddle demo

参考文献:

答案 1 :(得分:2)

检查一下:

<div style="background:black; height:100vh;"></div>
<div>Hello</div>
<div>World</div>

答案 2 :(得分:1)

你可以使用

height: 100vh;
width: 100vw;

无需绝对左上角;

相关问题