将页脚推到短页面的底部

Push footer to the bottom of a short page

我想将页脚推到页面底部,由于页面内容不多,页脚会向上浮动,不会移动到底部。

我尝试将我的页脚定位为固定元素作为解决方法,它有效,但在这种情况下无效:

在此维度中,页脚的行为与您看到的一样,这是完全符合预期的,因此显示了我的解决方法中的漏洞。

这是网站地址:https://n-ii-ma.github.io/Portfolio-Website/contact.html

这些是该部分的代码:

/* Contact Footer */

.contact-footer {
  position: fixed;
  bottom: 10px;
  left: 0;
  right: 0;
}
<body>
  <header>
    <h1 class="main-title">Nima's Portfolio</h1>
    <nav class="navigation">
      <ul>
        <li>
          <a href="./index.html">Home</a>
        </li>
        <li>
          <a href="./index.html#projects">Projects</a>
        </li>
        <li>
          <a href="./contact.html">Contact Me</a>
        </li>
      </ul>
    </nav>
  </header>
  <main>
    <section class="contact-section">
      <h2>Contact Me</h2>
      <p>Use the links below to contact me and I'll reach out to you as soon as possible</p>
      <div class="links">
        <a href="https://github.com/n-ii-ma" target="_blank">
          <i class="fab fa-github fa-3x"></i>
        </a>
        <a href="#">
          <i class="fas fa-envelope-square fa-3x"></i>
        </a>
      </div>
    </section>
  </main>
  <footer class="contact-footer">&copy; All Rights Reserved</footer>
</body>

有没有办法让我的页脚始终位于页面底部?

完全支持的简单解决方案是使用 Flexbox。

  1. 我们给 body 一个 min-height: 100vh 所以它至少跨越整个视口高度。
  2. 默认页边距body会默认让页面溢出。为了解决这个问题,我们需要重置边距:margin: 0
  3. 我们re-add一个填充。大多数浏览器的默认边距是 8px。所以我选择了那个。你可以拿任何你喜欢的。
  4. 由于box-modell,填充也会导致溢出。为了对抗我们使用:box-sizing: border-box
  5. 然后我们使用flexbox:display: flex.
  6. 为了保持正常的 block-level 行为,我们使用:flex-direction: column
  7. 要将页脚推到底部,我们使用:margin-top: auto;。如果页面内容小于视口高度,这会将页脚推到页面底部。

body {
  margin: 0;
  padding: 8px;
  box-sizing: border-box;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

footer {
  margin-top: auto;
}
<body>
  <header>
    <h1 class="main-title">Nima's Portfolio</h1>
    <nav class="navigation">
      <ul>
        <li>
          <a href="./index.html">Home</a>
        </li>
        <li>
          <a href="./index.html#projects">Projects</a>
        </li>
        <li>
          <a href="./contact.html">Contact Me</a>
        </li>
      </ul>
    </nav>
  </header>
  <main>
    <section class="contact-section">
      <h2>Contact Me</h2>
      <p>Use the links below to contact me and I'll reach out to you as soon as possible</p>
      <div class="links">
        <a href="https://github.com/n-ii-ma" target="_blank">
          <i class="fab fa-github fa-3x"></i>
        </a>
        <a href="#">
          <i class="fas fa-envelope-square fa-3x"></i>
        </a>
      </div>
    </section>
  </main>
  <footer class="contact-footer">&copy; All Rights Reserved</footer>
</body>