【问题标题】:Adjust background container to page height not screen height.将背景容器调整为页面高度而不是屏幕高度。
【发布时间】:2013-01-09 16:53:31
【问题描述】:

我的问题是我的背景容器只显示到屏幕底部。在那之后的部分我看不到它。我几乎尝试了一切,但似乎没有什么对我有用。我希望它根据页面大小进行调整。

<body>
<div id="profilebg">

<!-- Other divs -->

</div>
</body>

我的 CSS 是

html, body {
    height:100%;
}

#profilebg
{
    position: absolute;
    margin-left:10%;
    margin-right:10%;
    width:80%;
    background-color:#ffffff;
    height: 100%;
    top: 0;
    bottom: 0;
    display: block;
}

【问题讨论】:

  • 如果#profilebg 是你的后台容器,你为什么要使用绝对定位?
  • 我尝试不使用绝对定位,但这也不起作用。尝试了很多东西,阅读了很多文章,我在某个地方读到了这篇文章,所以想试一试。
  • 删除position: absolute;height: 100%;top: 0;bottom: 0;
  • 我同意,我个人尽量避免绝对定位。请使用相对定位查看我的编辑答案。

标签: css background containers


【解决方案1】:

如果您不指定高度,则默认为“自动”,由内容的高度决定。

如果您在内容中浮动某些内容,请务必添加一个具有 ccs 样式的元素 clear:both,以便父级可以正确确定其高度。

类似地,如果元素的任何子元素使用绝对定位,它将无法自动确定其高度,因为绝对定位的子元素不再与父元素在同一范围内。

工作风格示例如下:

html, body {
  height:100%;
}

#profilebg
{
    margin: 0 10%;
    background-color:#ffffff;
}

编辑:更简洁的 CSS 样式 - 宽度与边距是多余的

编辑2:添加关于绝对定位的行

编辑 3: 在以下 cmets 中实现请求的 Div 结构:

<div id="page-container">
    <div id="header-container">
        <!-- Put your header here -->
    </div>
    <div id="body-container">
        <div id="profilebg">
            <!-- Profile BG Container -->
        </div>
        <!-- Any other body content here -->
    </div>
    <div id="footer-container">
        <!-- Footer content here -->
    </div>
</div>

【讨论】:

  • 如果我从容器中删除所有绝对定位的 div,它就可以工作。知道是什么原因吗?
  • 当它有绝对定位的子代时,父代无法确定它的高度,因为绝对定位使它超出了父代的范围
  • @linpar 如果您告诉我们您正在尝试对某些元素的绝对定位做什么,那么可能会有适合您的解决方案
  • 非常感谢您的帮助。我真的很感激。
  • @linpar 这就是这个网站的全部意义
【解决方案2】:

以下内容似乎适用于您想要实现的目标。我已删除 bottom:0; 并将 height 更改为 min-height

html, body {   
    height:100%; 
}

#profilebg {
    position: absolute;
    margin-left:10%;
    margin-right:10%;
    width:80%;   
    min-height:100%;
    background-color:#ffffff;
    top: 0;
    display: block;   
}

编辑这是fiddle

EDIT 2 这是一个具有相对定位的fiddle

【讨论】:

  • 我猜它不适用于我的其他 div。我尝试了

    标签,它正在使用它们。

  • 如果您对 #profilebg 中包含的所有内容使用绝对定位,那么它将无法计算出初始高度。
  • 我正在对#profilebg 中存在的某些容器使用绝对定位,我尝试了相对定位,但这也不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-10
  • 1970-01-01
  • 2014-11-06
  • 1970-01-01
相关资源
最近更新 更多