首页 > 解决方案 > 将页脚粘贴到页面底部

问题描述

如果主高度小于文档的高度,如何让页脚粘在页面底部?
https://planbuildr.com/login?skin=purple
目前我正在这样做,但我认为这是错误的,因为内页(登录后)页脚位于屏幕下方。

<script>
$(document).ready(function()
{
    // Change height of container
    if ($("#main").height() < $(document).height())
     $("#main").height($(document).height() - 152); // 132
});
</script>

我不确定我是否应该只使用 CSS 解决方案。我不介意 JavaScript 是否用于检测高度。

带有 PHP 代码的 HTML 代码体是这样的:

<div id="container">
    <header style="background-color:#3264f2;height:43px">
        <?php require_once CB_DIR_UI.$CB['skin'].'/html/header.html'; ?>
    </header>

    <main id="main" style="width:calc(100% - 300px);margin:20px auto 0 auto;padding:10px;border:7.5px solid #666666;border-radius: 10px;background-color:#f6f7fa;overflow-y:auto">
        <?php require_once CB_DIR_UI.$CB['skin'].'/html/'.$CB['template_file']; ?>    
    </main>    

    <div class="clear"></div>    

    <footer style="margin-top:20px">
        <?php require_once CB_DIR_UI.$CB['skin'].'/html/footer.html'; ?>
    </footer>    

</div>

标签: javascriptcss

解决方案


您只能使用 flexbox 在 css 中实现这一点。第二个例子展示了当内容溢出页面时它是如何工作的。

body {
  margin: 0;
}

main {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

header, section, footer {
  padding: 8px;
}

section {
  flex: 1;
  background: silver;
}
<main>
  <header>Header</header>
  <section>Content</section>
  <footer>Footer</footer>
</main>

    body {
      margin: 0;
    }

    main {
      display: flex;
      flex-direction: column;
      height: 100vh;
    }

    header, section, footer {
      padding: 8px;
    }

    section {
      flex: 1;
      background: silver;
    }
<main>
  <header>Header</header>
  <section>
    Content<br/>Content<br/>Content<br/>Content<br/>Content<br/>Content<br/>Content<br/>Content<br/>Content<br/>Content<br/>Content<br/>Content<br/>Content<br/>Content<br/>Content<br/>Content<br/>
  </section>
  <footer>Footer</footer>
</main>


推荐阅读