【问题标题】:Sticky footer with a variable height具有可变高度的粘性页脚
【发布时间】:2014-10-25 08:12:37
【问题描述】:

我知道有很多相同的主题,但是有没有任何 CSS 方法可以将一个高度为 % 的页脚放在底部而不会因为绝对位置而溢出正文和页眉?

我正在尝试坚持这个:

html,body{
    height: 100%;
}

#header{
    background-color: yellow;
    height: 100px;
    width: 100%;
}

#holder {
    min-height: 100%;
    position:relative;
}

#body {
    padding-bottom: 100px;
}

#footer{
    background-color: lime;
    bottom: 0;
    height: 100%;
    left: 0;
    position: relative;
    right: 0;
}

使用 html :

<div id="holder">
    <div id="header">Title</div>
    <div id="body">Body</div>
    <div id="footer">Footer</div>
</div>

代码在这里:http://jsfiddle.net/TsRkB/

谢谢!

【问题讨论】:

标签: html css


【解决方案1】:

如果您使用 display:table 作为基础,那么您的粘性页脚可以是任意大小,并且会在内容增长时被下推。

http://dabblet.com/gist/5971212

html {
    height:100%;
    width:100%;
    }
body {
    height:100%;
    width:100%;
    display:table;
    table-layout:fixed;
    margin:0 auto;
    width:80%;
    }
.tr {
    display:table-row;
    background:turquoise
    }
section.tr {
    height:100%;
    background:yellow
    }

<header class="tr"> <h1>title</h1><p>make me grow</p></header>
<section class="tr"><article>article</article></section>
<footer class="tr"> <p>Footer</p><p>make me grow</p></footer>

【讨论】:

  • 谢谢!太完美了
  • 您能解释一下为什么会这样吗?我不明白中间的部分如何可以有 100% 的高度,而其他两个表格行显示页脚和页眉的高度不为零......
  • 因为我们使用 display:table 和 height : 100%;如果没有足够的内容来填充它们,这个高度将是 strecthcing 元素。如果您将其中之一设置为 100%;当其他人缩小其内容时,它将采用最大高度。一旦内容的高度超过 100%,整个容器就会增长,但永远不会低于 100% 的高度。就像
  • 没有 table-layout: fixed; 我在 IE 中遇到了一些宽度问题。内容溢出。
【解决方案2】:

所有其他解决方案都已过时并且有一个主要缺点:如果页脚的高度可变或未知,它们将不起作用。

随着CSS flex model 的出现,解决这个问题变得非常非常容易:虽然主要以在水平方向布局内容而闻名,但 Flexbox 实际上也适用于垂直布局问题。您所要做的就是将垂直部分包装在一个弹性容器中,然后选择要扩展的部分。它们会自动占用容器中的所有可用空间。

请注意标记和 CSS 的简单程度。没有桌子黑客或任何东西。

flex 模型是supported by all major browsers 以及据称是 IE11+,尽管我的 IE 还没有正确呈现这个 sn-p。

html, body {
  height: 100%;
}

#header {
  background: yellow;
  height: 100px;  /* can be variable as well */
}

#wrapper {
  display: flex;  /* use the flex model */
  min-height: 100%;
  flex-direction: column;  /* learn more: http://philipwalton.github.io/solved-by-flexbox/demos/sticky-footer/ */
}

#body {
  flex: 1;
  border: 1px solid orange;
}

#footer{
  background: lime;
}
<div id="wrapper">
  <div id="header">Title</div>
  <div id="body">Body</div>
  <div id="footer">
    Footer<br/>
    of<br/>
    variable<br/>
    height<br/>
  </div>
</div>

【讨论】:

    【解决方案3】:

    已为您修复它,基本上必须将页脚放在包装器之外并将其向上移动... http://jsfiddle.net/sMdmk/4/

    #footer{
    background-color: lime;
    bottom: 0;
    height: 10%;
    left: 0;
    position: relative;
    right: 0;
    top: -10%;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-24
      • 2013-10-13
      • 2015-02-11
      • 2012-04-29
      • 2011-05-24
      • 1970-01-01
      • 2013-09-07
      • 2013-01-12
      相关资源
      最近更新 更多