Html 如何让页脚停留在网页底部?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 22:11:33  来源:igfitidea点击:

How do you get the footer to stay at the bottom of a Web page?

csshtmlfootersticky-footer

提问by Bill the Lizard

I have a simple 2-column layout with a footer that clears both the right and left div in my markup. My problem is that I can't get the footer to stay at the bottom of the page in all browsers. It works if the content pushes the footer down, but that's not always the case.

我有一个简单的 2 列布局,带有一个页脚,可以清除标记中的左右 div。我的问题是我无法让页脚在所有浏览器中都停留在页面底部。如果内容将页脚向下推,它会起作用,但情况并非总是如此。

采纳答案by Staale

To get a sticky footer:

要获得粘性页脚:

  1. Have a <div>with class="wrapper"for your content.

  2. Right beforethe closing </div>of the wrapperplace the <div class="push"></div>.

  3. Right afterthe closing </div>of the wrapperplace the <div class="footer"></div>.

  1. 有一个<div>class="wrapper"您的内容。

  2. 收盘</div>的的wrapper地方 <div class="push"></div>

  3. 收盘</div>的的wrapper地方 <div class="footer"></div>

* {
    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 */
}

回答by Danield

Use CSS vh units!

使用 CSS vh 单位!

Probably the most obvious and non-hacky way to go about a sticky footer would be to make use of the new css viewport units.

处理粘性页脚的最明显和最简单的方法可能是使用新的css viewport units

Take for example the following simple markup:

以下面的简单标记为例:

<header>header goes here</header>
<div class="content">This page has little content</div>
<footer>This is my footer</footer>

If the header is say 80px high and the footer is 40px high, then we can make our sticky footer with one single ruleon the content div:

如果页眉高 80 像素,页脚高 40 像素,那么我们可以在内容 div 上使用一条规则制作粘性页脚:

.content {
    min-height: calc(100vh - 120px);
    /* 80px header + 40px footer = 120px  */
}

Which means: let the height of the content div be at least100% of the viewport height minus the combined heights of the header and footer.

这意味着:让内容 div 的高度至少为视口高度的 100% 减去页眉和页脚的组合高度。

That's it.

就是这样。

* {
    margin:0;
    padding:0;
}
header {
    background: yellow;
    height: 80px;
}
.content {
    min-height: calc(100vh - 120px);
    /* 80px header + 40px footer = 120px  */
    background: pink;
}
footer {
    height: 40px;
    background: aqua;
}
<header>header goes here</header>
<div class="content">This page has little content</div>
<footer>This is my footer</footer>

... and here's how the same code works with lots of content in the content div:

...这里是相同的代码如何处理内容 div 中的大量内容:

* {
    margin:0;
    padding:0;
}
header {
    background: yellow;
    height: 80px;
}
.content {
    min-height: calc(100vh - 120px);
    /* 80px header + 40px footer = 120px  */
    background: pink;
}
footer {
    height: 40px;
    background: aqua;
}
<header>header goes here</header>
<div class="content">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.
</div>
<footer>
    This is my footer
</footer>

NB:

注意:

1) The height of the header and footer must be known

1) 必须知道页眉页脚的高度

2) Old versions of IE (IE8-) and Android (4.4-) don't support viewport units. (caniuse)

2) 旧版本的 IE (IE8-) 和 Android (4.4-) 不支持视口单位。( caniuse)

3) Once upon a time webkit had a problem with viewport units within a calc rule. This has indeed been fixed (see here) so there's no problem there. However if you're looking to avoid using calc for some reason you can get around that using negative margins and padding with box-sizing -

3) 曾几何时,webkit 在计算规则中遇到了视口单位问题。这确实已修复(请参阅此处),因此没有问题。但是,如果您出于某种原因希望避免使用 calc,则可以使用负边距和使用 box-sizing 填充来解决这个问题 -

Like so:

像这样:

* {
    margin:0;padding:0;
}
header {
    background: yellow;
    height: 80px;
    position:relative;
}
.content {
    min-height: 100vh;
    background: pink;
    margin: -80px 0 -40px;
    padding: 80px 0 40px;
    box-sizing:border-box;
}
footer {
    height: 40px;
    background: aqua;
}
<header>header goes here</header>
<div class="content">Lorem ipsum 
</div>
<footer>
    This is my footer
</footer>

回答by gcedo

Sticky footer with display: flex

带有粘性页脚 display: flex

Solution inspired by Philip Walton's sticky footer.

Philip Walton 的粘性页脚启发的解决方案。

Explanation

解释

This solution is valid only for:

此解决方案仅适用于

  • Chrome ≥ 21.0
  • Firefox ≥ 20.0
  • Internet Explorer ≥ 10
  • Safari ≥ 6.1
  • 铬 ≥ 21.0
  • 火狐 ≥ 20.0
  • Internet Explorer ≥ 10
  • Safari ≥ 6.1

It is based on the flexdisplay, leveraging the flex-growproperty, which allows an element to growin either heightor width(when the flow-directionis set to either columnor rowrespectively), to occupy the extra space in the container.

它基于flexdisplay,利用flex-grow允许元素在高度宽度增长(当设置为任一或分别)的属性来占用容器中的额外空间。flow-directioncolumnrow

We are going to leverage also the vhunit, where 1vhis defined as:

我们要充分利用也是vh单元,其中1vh定义为

1/100th of the height of the viewport

视口高度的 1/30

Therefore a height of 100vhit's a concise way to tell an element to span the full viewport's height.

因此,100vh它的高度是告诉元素跨越整个视口高度的简洁方式。

This is how you would structure your web page:

这是您构建网页的方式:

----------- body -----------
----------------------------

---------- footer ----------
----------------------------

In order to have the footer stick to the bottom of the page, you want the space between the body and the footer to grow as much as it takes to push the footer at the bottom of the page.

为了让页脚粘在页面底部,您希望正文和页脚之间的空间增长到将页脚推到页面底部所需的空间。

Therefore our layout becomes:

因此我们的布局变为:

----------- body -----------
----------------------------

---------- spacer ----------
                             <- This element must grow in height
----------------------------

---------- footer ----------
----------------------------

Implementation

执行

body {
    margin: 0;
    display: flex;
    flex-direction: column;
    min-height: 100vh;
}

.spacer {
    flex: 1;
}

/* make it visible for the purposes of demo */
.footer {
    height: 50px;
    background-color: red;
}
<body>
    <div class="content">Hello World!</div>
    <div class="spacer"></div>
    <footer class="footer"></footer>
</body>

You can play with it at the JSFiddle.

你可以在JSFiddle玩它。

Safari quirks

Safari 的怪癖

Be aware that Safari has a flawed implementation of the flex-shrinkproperty, which allows items to shrink more than the minimum height that would be required to display the content. To fix this issue you will have to set the flex-shrinkproperty explicitly to 0 to the .contentand the footerin the above example:

请注意,Safariflex-shrink属性的实现缺陷,它允许项目缩小到超过显示内容所需的最小高度。要解决此问题,您必须在上面的示例中将flex-shrink属性显式设置为 0.content和 the footer

.content { flex-shrink: 0; }
.footer  { flex-shrink: 0; }

回答by Jimmy

You could use position: absolutefollowing to put the footer at the bottom of the page, but then make sure your 2 columns have the appropriate margin-bottomso that they never get occluded by the footer.

您可以使用position: absolute以下内容将页脚放在页面底部,但请确保您的 2 列具有适当的内容,margin-bottom以便它们永远不会被页脚遮挡。

#footer {
    position: absolute;
    bottom: 0px;
    width: 100%;
}
#content, #sidebar { 
    margin-bottom: 5em; 
}

回答by Sophivorus

Here is a solution with jQuery that works like a charm. It checks if the height of the window is greater than the height of the body. If it is, then it changes the margin-top of the footer to compensate. Tested in Firefox, Chrome, Safari and Opera.

这是一个使用 jQuery 的解决方案,它就像一个魅力。它检查窗口的高度是否大于身体的高度。如果是,则它会更改页脚的顶部边距以进行补偿。在 Firefox、Chrome、Safari 和 Opera 中测试。

$( function () {

    var height_diff = $( window ).height() - $( 'body' ).height();
    if ( height_diff > 0 ) {
        $( '#footer' ).css( 'margin-top', height_diff );
    }

});

If your footer already has a margin-top (of 50 pixels, for example) you will need to change the last part for:

如果您的页脚已经有一个顶部边距(例如 50 像素),您将需要更改最后一部分:

css( 'margin-top', height_diff + 50 )

回答by Raleigh Buckner

Set the CSS for the #footerto:

将 CSS 设置#footer为:

position: absolute;
bottom: 0;

You will then need to add a paddingor marginto the bottom of your #sidebarand #contentto match the height of #footeror when they overlap, the #footerwill cover them.

然后,您需要在底部添加padding或并匹配它们的高度或当它们重叠时,将覆盖它们。margin#sidebar#content#footer#footer

Also, if I remember correctly, IE6 has a problem with the bottom: 0CSS. You might have to use a JS solution for IE6 (if you care about IE6 that is).

另外,如果我没记错的话,IE6 的bottom: 0CSS有问题。您可能必须为 IE6 使用 JS 解决方案(如果您关心 IE6)。

回答by Temani Afif

A similar solution to @gcedobut without the need of adding an intermediate content in order to push the footer down. We can simply add margin-top:autoto the footer and it will be pushed to the bottom of the page regardless his height or the height of the content above.

@gcedo类似的解决方案,但无需添加中间内容以将页脚向下推。我们可以简单地添加margin-top:auto到页脚,不管他的高度或上面内容的高度,它都会被推到页面的底部。

body {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  margin:0;
}

.content {
  padding: 50px;
  background: red;
}

.footer {
  margin-top: auto;
  padding:10px;
  background: green;
}
<div class="content">
  some content here
</div>
<footer class="footer">
  some content
</footer>

回答by ferit

enter image description here

在此处输入图片说明

index.html:

索引.html:

<!DOCTYPE html>

<html>
 <head>
   <link rel="stylesheet" type="text/css" href="main.css" />
 </head>

<body>
 <div id="page-container">
   <div id="content-wrap">
     <!-- all other page content -->
   </div>
   <footer id="footer"></footer>
 </div>
</body>

</html>

main.css:

主文件:

#page-container {
  position: relative;
  min-height: 100vh;
}

#content-wrap {
  padding-bottom: 2.5rem;    /* Footer height */
}

#footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 2.5rem;            /* Footer height */
}

Source: https://www.freecodecamp.org/news/how-to-keep-your-footer-where-it-belongs-59c6aa05c59c/

来源:https: //www.freecodecamp.org/news/how-to-keep-your-footer-where-it-belongs-59c6aa05c59c/

回答by Daniel Alsaker

I have myself struggled with this sometimes and I always found that the solution with all those div's within each other was a messy solution. I just messed around with it a bit, and I personally found out that this works and it certainly is one of the simplest ways:

我自己有时也为此而苦苦挣扎,我总是发现所有这些 div 相互之间的解决方案是一个混乱的解决方案。我只是把它弄乱了一点,我个人发现这很有效,而且它肯定是最简单的方法之一:

html {
    position: relative;
}

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

footer {
    position: absolute;
    bottom: 0;
}

What I like about this is that no extra HTML needs to be applied. You can simply add this CSS and then write your HTML as whenever

我喜欢这一点的是不需要应用额外的 HTML。你可以简单地添加这个 CSS 然后像任何时候一样编写你的 HTML

回答by VXp

Since the Gridsolution hasn't been presented yet, here it is, with just two declarationsfor the parent element, if we take the height: 100%and margin: 0for granted:

由于电网的解决方案尚未提交,这里是,只有两个声明父元素,如果我们把height: 100%margin: 0理所当然:

html, body {height: 100%}

body {
  display: grid; /* generates a block-level grid */
  align-content: space-between; /* places an even amount of space between each grid item, with no space at the far ends */
  margin: 0;
}

.content {
  background: lightgreen;
  /* demo / for default snippet window */
  height: 1em;
  animation: height 2.5s linear alternate infinite;
}

footer {background: lightblue}

@keyframes height {to {height: 250px}}
<div class="content">Content</div>
<footer>Footer</footer>

The items are evenly distributed within the alignment container along the cross axis. The spacing between each pair of adjacent items is the same. The first item is flush with the main-start edge, and the last item is flush with the main-end edge.

项目沿交叉轴均匀分布在对齐容器内。每对相邻物品之间的间距相同。第一项与主起始边齐平,最后一项与主结束边齐平。