即使使用动态高度网站,如何将页脚保持在底部

新手上路,请多包涵

当我有一个使用 CSS 动态设置高度(例如从数据库获取信息)的页面时,如何将页脚 div 始终保持在窗口底部?


如果你想使用 jQuery,我想出了这个并且工作正常:

设置页脚的 CSS:

 #footer { position:absolute; width:100%; height:100px; }

设置脚本:

 <script>
  x = $('#div-that-increase-height').height()+20; // +20 gives space between div and footer
  y = $(window).height();
  if (x+100<=y){ // 100 is the height of your footer
    $('#footer').css('top', y-100+'px');// again 100 is the height of your footer
    $('#footer').css('display', 'block');
  }else{
    $('#footer').css('top', x+'px');
    $('#footer').css('display', 'block');
  }
</script>

这个脚本必须在你的代码的末尾;

原文由 Rafael Fonseca 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 267
2 个回答

我相信您正在寻找 粘性页脚

试试这个: https ://web.archive.org/web/20161117191810/http://ryanfait.com/sticky-footer/(存档)

从上面的文章:

布局.css:

 * {
    margin: 0;
}
html, body {
    height: 100%;
}
.wrapper {
    min-height: 100%;
    height: auto !important;
    height: 100%;
    margin: 0 auto -142px; /* the bottom margin is the negative value of the footer's height */
}
.footer, .push {
    height: 142px; /* .push must be the same height as .footer */
}

/*

Sticky Footer by Ryan Fait
http://ryanfait.com/

*/

html页面:

 <html>
    <head>
        <link rel="stylesheet" href="layout.css" ... />
    </head>
    <body>
        <div class="wrapper">
            <p>Your website content here.</p>
            <div class="push"></div>
        </div>
        <div class="footer">
            <p>Copyright (c) 2008</p>
        </div>
    </body>
</html>

原文由 agarcian 发布,翻译遵循 CC BY-SA 4.0 许可协议

我认为这将解决您所有的问题:

     <script>

  $(document).ready(function() {

   var docHeight = $(window).height();
   var footerHeight = $('#footer').height();
   var footerTop = $('#footer').position().top + footerHeight;

   if (footerTop < docHeight) {
    $('#footer').css('margin-top', 10+ (docHeight - footerTop) + 'px');
   }
  });
 </script>

您至少需要一个带有 \#footer 的元素

当内容适合屏幕时不需要滚动条,只需将 10 的值更改为 0 如果内容不适合屏幕,滚动条将显示。

原文由 HenryW 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题