【问题标题】:Most efficient and compatible way to achieve docked footer实现停靠页脚的最有效和兼容的方式
【发布时间】:2019-04-09 22:09:28
【问题描述】:

我正在尝试在 CSS 模板中执行以下操作:

  1. 当内容不足时将页脚停靠在底部 填满页面
  2. 在整个宽度上拉伸页眉和页脚背景
  3. 将所有内容放在页面中间

这是我在此处的帮助下创建的代码: http://tinkerbin.com/lCNs7Upq

我的问题是,我已经看到了一些实现这一目标的方法。这是最好的吗?还得有空的 div 似乎很可惜,这是一个麻烦吗?

【问题讨论】:

    标签: html css sticky-footer


    【解决方案1】:

    您可以使用 CSS 修复和元素到页脚:

    position: fixed;
    bottom: 0;
    

    但是,我想弄清楚你到底想做什么。

    如果是 div,页眉和页脚应该自动 100% 跨页。

    你的中间部分可以设置为 height: auto;通过 css 并会填满视口,将页脚一直推到底部,但要做到这一点,您还必须将 body 设置为 100% 才能使其工作。

    html, body, #content {
        height: 100%;
        min-height: 100%;
    }
    #header {
        height: 100px;
        width: 100%;
        background: blue;
        position: fixed;
        top: 0;
    }
    #content {
        height: auto;
        margin: 100px auto;
        background: green;
    }
    #footer {
        position: fixed;
        bottom: 0;
        height: 100px;
        width: 100%;
        background: red;
    }
    

    您的 HTML 应该看起来像这样:

    <div id="header"></div>
    <div id="content"></div>
    <div id="footer"></div>
    

    工作示例:http://jsfiddle.net/s4rT3/1/

    【讨论】:

    • background-position: fixed 不会锚定元素。 height: auto 不会导致 div '填满视口'。你试过了吗?
    • 我忘记添加 html,正文。这将填满整个视口。 jsfiddle.net/s4rT3
    • 好吧,我看到background-position: fixed 消失了。正是#content {height: 100%} 导致#content 填满屏幕。我仍然认为 Coyier 的示例更好,因为它没有在您的示例中看到的时髦滚动条行为。 (当您要滚动的内容区域时,整个页面的滚动条)
    • 感谢您的回复。确实,这是一个很好的解决方案,但是滚动条问题很痛苦jsfiddle.net/s4rT3/2
    【解决方案2】:

    这是我见过的最好的例子:

    http://css-tricks.com/snippets/css/sticky-footer/

    * {
      margin: 0;
    }
    html, body {
      height: 100%;
    }
    .page-wrap {
      min-height: 100%;
      /* equal to footer height */
      margin-bottom: -142px; 
    }
    .page-wrap:after {
      content: "";
      display: block;
    }
    .site-footer, .page-wrap:after {
      height: 142px; 
    }
    .site-footer {
      background: orange;
    }
    <div class="page-wrap">
      
      Content!
          
    </div>
    
    <footer class="site-footer">
      I'm the Sticky Footer.
    </footer>

    更新:在 2019 年使用 flex 是更好的选择。

    【讨论】:

    • 这是最好的答案:p
    • 对不起 necro - 它被否决的原因可能是因为它只是一个链接。这意味着内容可能会更改和/或变得不可用。
    猜你喜欢
    • 1970-01-01
    • 2010-10-07
    • 1970-01-01
    • 2014-12-15
    • 2014-01-12
    • 2022-11-14
    • 1970-01-01
    • 2011-08-20
    • 1970-01-01
    相关资源
    最近更新 更多