HTML,CSS粘性底部(内容增长)

5
我将尝试为一个高度动态增长的div设置一个粘性底部。该div需要浮动在页面中央(距离左右两侧相同)。
以下是我所拥有的HTML代码(已去除无关内容):
<html>
<body>
  <div class="bodybackground">
    <div class="container"><!-- floats in the middle -->
      <div class="mainContainer"><!-- different color etc -->
        <!-- content with dynamic height -->
      </div>
      <footer class="pagefooter"></footer>
    </div> 
  </div>
</body>
</html>

以下是相关的 CSS (已去除无关部分):
html {
  height: 100%;
  margin: 0px;
  padding: 0px; 
}
body { 
  margin: 0px;
  height: 100%; 
}
.bodybackground {
  height: 100%;
  min-height: 100%;
}

.container { 
  min-height: 100%;
  display: inline-block; /* needed make it float in the middle of body */
  top: 0px;
  position: relative;
  padding: 0px;
  padding-bottom: 158px; /* height of footer */
}
.mainContainer {
  position: absolute;
  height: 100%;
  overflow: auto;
}
.pagefooter {
  position: absolute;
  bottom: 0px;
  margin: 0px;
  padding: 0px;
  height: 158px; 
}
的内容会漂浮到页脚后面,而不是页脚在页面最底部。我尝试了各种方法,除了那些要求我更改容器的display属性的示例,因为我需要它保持在中间漂浮。

有什么线索可以帮助我解决问题吗?谢谢!


我需要再调整一下.push,但这解决了问题!感谢您的快速回答!

2个回答

8
通过使用绝对定位,页脚和主容器的位置取决于您放置它们的位置。如果您使用绝对定位并将页脚设置为底部,则它将粘在视口的底部。
对于粘性布局,应使用相对单位和必要的正确高度。
html, body { width:100%; height:100%; }
#wrap { 
min-height:100%;
height:auto !important;
height:100%;    
margin: 0 auto -158px;  /* Bottom value must = footer height */
}

.pagefooter, .push { width:100%; height:158px; position:relative; bottom:0; }

订单按照以下顺序进行:
 <div id="wrap">
 <!--All of your content goes here-->
 <div class="push"></div>
 </div>
 <div class="pagefooter"></div>

那样,页脚总是有足够的空间并设置到底部。在wrap内使用margin:auto将居中wrap(只要它不是width:100%,它就可以在没有inline的情况下居中)。

0

所以,您正在寻找一个带有居中组件的粘性页脚。最简单的方法是创建一个固定位置元素,其中包含一个居中的div(基本上是具有指定宽度和margin: auto的div)。

您可以在http://jsfiddle.net/gHDd8/上看到这个示例 - CSS基本上是

.outerBlockElement {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
}

.innerBlockElement {
    width: 50%;
    margin: auto;
}

HTML的等效内容是什么

<div class="outerBlockElement">
    <p class="innerBlockElement">I am sticky footer text!</p>
</div>

固定页脚位于视口底部,页面居中显示。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接