CSS使HTML页面页脚以最小高度留在页面底部,但不与页面重叠

新手上路,请多包涵

我有以下页面(死链接: http://www.workingstorage.com/Sample.htm )有一个页脚,我无法将其放在页面底部。

我希望页脚

  • 当页面较短且屏幕未填满时,贴在窗口底部,并且
  • 当内容超过一屏时(而不是重叠内容),停留在文档末尾并正常向下移动。

CSS是继承的,让我感到困惑。我似乎无法正确更改它以在内容上设置最小高度或使页脚进入底部。

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

阅读 543
2 个回答

一个简单的方法是使页面的主体 100% 也具有 min-height100% 。如果页脚的高度没有改变,这可以正常工作。

给页脚一个负边距顶部:

 footer {
    clear: both;
    position: relative;
    height: 200px;
    margin-top: -200px;
}

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

以下是我的4种不同方法:

在每个示例中,文本都是可自由编辑的,以说明内容在不同场景中的呈现方式。


1)弹性盒子

 body{ min-height: 100vh; margin:0; }

header{ min-height:50px; background:lightcyan; }
footer{ min-height:50px; background:PapayaWhip; }

/* The article fills all the space between header & footer */
body{ display:flex; flex-direction:column; }
article{ flex:1; }
 <body>
  <header contentEditable>Header</header>
  <article contentEditable>Content</article>
  <footer contentEditable>Footer</footer>
</body>

2)网格

 body{
  min-height: 100vh;
  margin: 0;

  display: grid;
  grid-template-rows: auto 1fr auto;
}

header{
  min-height:50px;
  background:lightcyan;
}

footer{
  min-height:50px;
  background:PapayaWhip;
}
 <body>
  <header contentEditable>Header</header>
  <article contentEditable>Content</article>
  <footer contentEditable>Footer</footer>
</body>

下面的这个方法通过在 --- 上放置一个 ::after body 元素来使用“技巧”,并将其设置为具有页脚的 确切 高度,因此它将占据完全相同的高度页脚的空间,所以当页脚 absolute 定位在它上面时,看起来页脚真的占用了空间并消除了它的绝对定位的负面影响(例如,越过正文的内容)

3) position:absolute (无 动态 页脚高度)

 body{ min-height:100vh; margin:0; position:relative; }
header{ min-height:50px; background:lightcyan; }
footer{ background:PapayaWhip; }

/* Trick: */
body {
  position: relative;
}

body::after {
  content: '';
  display: block;
  height: 50px; /* Set same as footer's height */
}

footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 50px;
}
 <body>
  <header contentEditable>Header</header>
  <article contentEditable>Content</article>
  <footer contentEditable>Footer</footer>
</body>

4)表格布局

 html{ height:100%; }
body { min-height:100%;  margin:0; }

header {
  height: 50px;
  background: lightcyan;
}

article {
  height: 1%;
}

footer {
  height: 50px;
  background: PapayaWhip;
}

/**** Trick: ****/

body {
  display: table;
  width: 100%;
}

body > footer {
   display: table-row;
}
 <body>
  <header contentEditable>Header</header>
  <article contentEditable>Content</article>
  <footer contentEditable>Footer</footer>
</body>

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

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