【问题标题】:Absolute positioned DIV to be 100% of body height绝对定位的 DIV 为身高的 100%
【发布时间】:2016-07-31 22:50:19
【问题描述】:

我想要一个覆盖整个页面正文的 div,即使内容必须滚动。

典型的做法是使用绝对定位的 div,同时在 html 和 body 上设置 100% 的高度。

但是,如果页面上的其他内容比屏幕上的内容长,我的 100% 高度 div 只会覆盖窗口的可见区域,并且不会一直延伸到页面末尾。

示例:http://jsbin.com/wuqezaceteme/1/

CSS:

body, html {
  margin:0;
  padding:0;
  height:100%;
  width:100%;
}

body {
  position:relative;
}

.wrapper {
  position:absolute; /* can't use fixed */
  background:yellow;
  height:100%;
  width:100%;
  top:0;
  left:0;
}

.box {
  height:2200px;
}

HTML:

 <div class="wrapper">
 Scroll down (yellow box does not go to bottom when scrolling)
 </div>

 <div class="box">box</div>

</body>

【问题讨论】:

  • body, html 中删除height:100%
  • 请问为什么不能用fixed?
  • @lolka_bolka 我不能使用 fixed,因为我的包装器实际上将包含另一个 div,我需要相对于滚动内容保持静态。

标签: html css css-position


【解决方案1】:

这可能对其他人有所帮助,因为这是一个似乎已经得到解答的老问题。

主要问题是您的 div 绑定到视口而不是主体。 既然你希望它绑定到身体使用:-

    body {
        position: relative;
    }

也不要在正文或 html 中添加 height:100%(这不是必需的)。
那应该这样做。现在你的 .wrapper div 将 100% 进入你的身体。即使您滚动页面,它也会保持 100%,因为它已绑定到正文。

【讨论】:

    【解决方案2】:

    你的身体有一个默认的height:100%,这是你需要使高度自动的窗口的初始高度,或者你需要从你的样式中删除它

    body, html {
      margin:0;
      padding:0;
      <--height:100%;--> Removed
      width:100%;
    }
    

    Working demo

    【讨论】:

    • body标签去掉高度的问题是,如果内容较小,div不会覆盖整个窗口。尝试将 .box 的高度链接到 200px 以了解我的意思。
    猜你喜欢
    • 2015-07-22
    • 2012-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-11
    • 2019-06-20
    • 2014-02-10
    相关资源
    最近更新 更多