I have a div element on my page with its height set to 100%. The height of the body is also set to 100%. The inner div has a background and all that and is different from the body background. This works for making the div height 100% of the browser screen height, but the problem is I have content inside that div that extends vertically beyond the browser screen height. When I scroll down, the div ends at the point at which you had to begin scrolling the page, but the content overflows beyond that. How do I make the div always go all the way to the bottom to fit the inner content?

这是我的CSS的简化:

body {
    height:100%;
    background:red;
}

#some_div {
    height:100%;
    background:black;
}

一旦我滚动页面,黑色就结束了,内容就会流向红色背景。不管我在#some_div上设置的位置是相对的还是绝对的,问题都发生了。#some_div中的内容大多是绝对定位的,并且它是从数据库动态生成的,因此无法预先知道它的高度。

编辑:下面是问题的截图:


当前回答

设置高度为auto,最小高度为100%。这应该可以解决大多数浏览器的问题。

body {
  position: relative;
  height: auto;
  min-height: 100% !important;
}

其他回答

设置高度为auto,最小高度为100%。这应该可以解决大多数浏览器的问题。

body {
  position: relative;
  height: auto;
  min-height: 100% !important;
}
#some_div {    
  height: fit-content;
}

https://developer.mozilla.org/en-US/docs/Web/CSS/fit-content

使用flex

.parent{
    display: flex
}

.fit-parent{
    display: flex;
    flex-grow: 1
}

通常,当父Div的子元素被浮动时,就会出现这个问题。以下是该问题的最新解决方案:

在你的CSS文件中写入下面的类。clearfix和伪选择器

.clearfix:after {
content: "";
display: table;
clear: both;
}

然后,在你的HTML中,添加.clearfix类到你的父Div中。例如:

<div class="clearfix">
    <div></div>
    <div></div>
</div>

它应该一直工作。您可以将类名调用为.group而不是.clearfix,因为这将使代码更具语义性。注意,在双引号“”之间的Content值中不需要添加点甚至空格。另外,overflow: auto;也许可以解决问题,但它会导致其他问题,如显示滚动条,不建议使用。

来源:Lisa Catalano和Chris Coyier的博客

没有位置的覆盖:固定

我在最近的菜单中发现了一个非常酷的方法,那就是将正文设置为:

position: relative

并像这样设置你的包装器类:

#overlaywrapper {
    position: absolute;
    top: 0;
    width: 100%;
    height: 100%;
    background: #00000080;
    z-index: 100;
}

这意味着你不必设置位置固定,仍然可以允许滚动。我用这个来覆盖非常大的菜单。