实现一个stick-footer布局

实现 stick-footer 布局,也就是让页脚始终贴在页面底部,即使内容不足以撑满整个视口高度。以下是几种常见的实现方法,并附带代码示例:

1. Flexbox 布局:

这是现代前端最推荐的 stick-footer 实现方式,简洁且兼容性好。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Stick Footer with Flexbox</title>
  <style>
    body {
      display: flex;
      flex-direction: column;
      min-height: 100vh; /* 关键:确保 body 至少占据整个视口高度 */
      margin: 0;
    }
    main {
      flex: 1; /* 关键:让 main 内容占据剩余空间 */
    }
    footer {
      background-color: #f0f0f0;
      padding: 20px;
    }
  </style>
</head>
<body>
  <main>
    <h1>Main Content</h1>
    <p>This is the main content of the page.</p>
  </main>
  <footer>
    <p>This is the footer.</p>
  </footer>
</body>
</html>

关键点:

  • body { display: flex; flex-direction: column; min-height: 100vh; }: 将 body 设置为 flex 容器,垂直排列,并确保其最小高度为视口高度。
  • main { flex: 1; }: 让 main 元素占据剩余空间,将 footer 推到底部。

2. Grid 布局:

Grid 布局也能轻松实现 stick-footer,与 Flexbox 类似。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Stick Footer with Grid</title>
  <style>
    body {
      display: grid;
      min-height: 100vh;
      grid-template-rows: 1fr auto; /* 关键:1fr 占据剩余空间,auto 自适应 footer 高度 */
      margin: 0;
    }
    main {

    }
    footer {
      background-color: #f0f0f0;
      padding: 20px;
    }
  </style>
</head>
<body>
  <main>
    <h1>Main Content</h1>
    <p>This is the main content of the page.</p>
  </main>
  <footer>
    <p>This is the footer.</p>
  </footer>
</body>
</html>

关键点:

  • grid-template-rows: 1fr auto;: 1fr 使 main 占据剩余空间,auto 使 footer 自适应高度。

3. 绝对定位/负边距 (较旧的方法,不推荐):

这种方法需要一些技巧,并且在某些情况下可能不如 Flexbox 和 Grid 灵活。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Stick Footer with Positioning</title>
  <style>
    html, body {
      height: 100%;
      margin: 0;
    }
    .wrapper {
      min-height: 100%;
      position: relative;
    }
    main {
      padding-bottom: 50px; /* footer 的高度 */
    }
    footer {
      position: absolute;
      bottom: 0;
      width: 100%;
      height: 50px;
      background-color: #f0f0f0;
      padding: 20px;
    }
  </style>
</head>
<body>
  <div class="wrapper">
    <main>
      <h1>Main Content</h1>
      <p>This is the main content of the page.</p>
    </main>
    <footer>
      <p
posted @   王铁柱6  阅读(3)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示