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

更新:

它在 Firefox 中无法正常工作。当页面上没有足够的内容将页脚一直推到浏览器窗口的底部时,我会在页脚下方看到一条背景色。不幸的是,这是页面的默认状态。

有帮助吗?

解决方案

要获得粘性页脚:

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

其他提示

使用 CSS vh 单位!

处理粘性页脚最明显且最简单的方法可能是利用新的 CSS 视口单位.

以以下简单标记为例:

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

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

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

意思是:设内容 div 的高度为 至少 100% 视口高度减去页眉和页脚的总高度。

就是这样。

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

...下面是相同的代码如何处理内容 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>

注意:

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

2)旧版本的IE(IE8-)和Android(4.4-)不支持视口单位。(我可以用吗)

3) 曾几何时,webkit 在计算规则中的视口单位方面存在问题。这确实已修复(看这里)所以那里没有问题。但是,如果您出于某种原因希望避免使用 calc,您可以使用负边距和填充框大小来解决这个问题 -

就像这样:

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

粘性页脚 display: flex

解决方案的灵感来自 菲利普·沃尔顿的粘性页脚.

解释

这个解决方案是 仅适用于:

  • 铬≥21.0
  • 火狐浏览器≥20.0
  • 互联网浏览器≥10
  • Safari ≥ 6.1

它基于 flex 展示, ,利用 flex-grow 属性,它允许元素 生长 在任一 高度 或者 宽度 (当。。。的时候 flow-direction 设置为 column 或者 row 分别),以占用容器中的额外空间。

我们还将利用 vh 单位,其中 1vh定义为:

视口高度的 1/100

因此高度为 100vh 这是告诉元素跨越整个视口高度的简洁方法。

这就是您构建网页的方式:

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

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

为了使页脚粘在页面底部,您希望正文和页脚之间的空间尽可能增大,以将页脚推到页面底部。

因此我们的布局变成:

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

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

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

执行

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>

您可以在以下位置玩它 JSFiddle.

野生动物园的怪癖

请注意,Safari 有一个 的执行有缺陷 flex-shrink 财产, ,它允许项目缩小到超过显示内容所需的最小高度。要解决此问题,您必须设置 flex-shrink 属性显式地设置为 0 到 .contentfooter 在上面的例子中:

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

你可以使用 position: absolute 按照以下步骤将页脚放在页面底部,但随后确保您的 2 列具有适当的内容 margin-bottom 这样它们就不会被页脚遮挡。

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

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

$( function () {

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

});

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

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

设置 CSS 为 #footer 到:

position: absolute;
bottom: 0;

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

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

类似的解决方案 @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>

使用绝对定位和 z 索引,使用以下步骤在任何分辨率下创建粘性页脚 div:

  • 创建一个页脚 div position: absolute; bottom: 0; 和所需的高度
  • 设置页脚的内边距以在内容底部和窗口底部之间添加空白
  • 创建一个容器 div 将正文内容包裹起来 position: relative; min-height: 100%;
  • 在主要内容中添加底部填充 div 等于高度加上页脚的内边距
  • 设置 z-index 页脚的大小大于容器的大小 div 如果页脚被剪裁

这是一个例子:

    <!doctype html>
    <html>
    <head>
      <title>Sticky Footer</title>
      <meta charset="utf-8">
      <style>
      .wrapper { position: relative; min-height: 100%; }
      .footer { position: absolute; bottom:0; width: 100%; height: 200px; padding-top: 100px; background-color: gray; }
      .column { height: 2000px; padding-bottom: 300px; background-color: green; }
     /* Set the `html`, `body`, and container `div` to `height: 100%` for IE6 */

      </style>
    </head>
    <body>
      <div class="wrapper">
        <div class="column">
          <span>hello</span>
        </div>
        <div class="footer">
          <p>This is a test. This is only a test...</p>
        </div>
      </div>
    </body>
    </html>

尝试在内容和侧边栏周围放置一个容器 div(带有溢出:自动)。

如果这不起作用,您是否有页脚显示不正确的屏幕截图或示例链接?

一种解决方案是设置盒子的最小高度。不幸的是,似乎 IE 不太支持 (惊喜)。

这些纯 CSS 解决方案都不能与动态调整内容大小(至少在 Firefox 和 Safari 上)一起正常工作,例如,如果您在容器 div、页面上设置了背景,然后调整 div 内的表格大小(添加几行),则表格可以伸出样式区域的底部,即,您可以将一半的表格在黑色主题上显示为白色,一半的表格完全白色,因为字体颜色和背景颜色都是白色的。主题滚轮页面基本上无法修复此问题。

嵌套 div 多列布局是一个丑陋的黑客,而用于粘贴页脚的 100% 最小高度主体/容器 div 是一个更丑陋的黑客。

唯一适用于我尝试过的所有浏览器的非脚本解决方案:一个更简单/更短的表格,带有 thead(用于页眉)/tfoot(用于页脚)/tbody(td 用于任意数量的列)和 100% 高度。但这有语义和 SEO 缺点(tfoot 必须出现在 tbody 之前。不过,ARIA 角色可能有助于体面的搜索引擎)。

CSS:

  #container{
            width: 100%;
            height: 100vh;
            }
 #container.footer{
            float:left;
            width:100%;
            height:20vh;
            margin-top:80vh;
            background-color:red;
            }

HTML:

           <div id="container">
               <div class="footer">
               </div>
           </div>

如果您正在寻找与页面底部对齐的响应式页脚,这应该可以解决问题,并且始终保持上边距为视口高度的 80%。

对于这个问题,我看到的许多答案都很笨拙,难以实现且效率低下,所以我想我应该尝试一下并提出我自己的解决方案,该解决方案只是一点点 css 和 html

html,
body {
  height: 100%;
  margin: 0;
}
.body {
  min-height: calc(100% - 2rem);
  width: 100%;
  background-color: grey;
}
.footer {
  height: 2rem;
  width: 100%;
  background-color: yellow;
}
<body>
  <div class="body">test as body</div>
  <div class="footer">test as footer</div>
</body>

这是通过设置页脚的高度,然后使用 css calc 计算出页脚仍位于底部的页面的最小高度来实现的,希望这可以帮助一些人:)

我自己有时也遇到过这个问题,而且我总是发现所有这些 div 彼此内部的解决方案是一个混乱的解决方案。我只是稍微搞了一下,我个人发现这是可行的,而且它肯定是最简单的方法之一:

html {
    position: relative;
}

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

footer {
    position: absolute;
    bottom: 0;
}

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

很多人都在这里给出了这个简单问题的答案,但我要补充一件事,考虑到在我弄清楚自己做错了什么之前我是多么沮丧。

正如前面提到的,最直接的方法就是这样..

html {
    position: relative;
    min-height: 100%;
}

body {
    background-color: transparent;
    position: static;
    height: 100%;
    margin-bottom: 30px;
}

.site-footer {
    position: absolute;
    height: 30px;
    bottom: 0px;
    left: 0px;
    right: 0px;
}

然而,帖子中没有提到的属性(大概是因为它通常是默认的)是 位置:静止的 在身体标签上。相对位置不起作用!

我的 WordPress 主题覆盖了默认的正文显示,这让我困惑了很长一段时间。

我知道一个旧线程,但如果您正在寻找响应式解决方案,这个 jQuery 添加将有所帮助:

$(window).on('resize',sticky);
$(document).bind("ready", function() {
   sticky();
});

function sticky() {
   var fh = $("footer").outerHeight();
   $("#push").css({'height': fh});
   $("#wrapper").css({'margin-bottom': -fh});
}

完整指南可以在这里找到: https://pixeldesigns.co.uk/blog/responsive-jquery-sticky-footer/

我创建了一个非常简单的库 https://github.com/ravinderpayal/FooterJS

使用起来非常简单。包含库后,只需调用这行代码即可。

footer.init(document.getElementById("ID_OF_ELEMENT_CONTAINING_FOOTER"));

通过使用不同的参数/id 调用上述函数,可以动态更改页脚。

footer.init(document.getElementById("ID_OF_ANOTHER_ELEMENT_CONTAINING_FOOTER"));

注意:- 您不必更改或添加任何 CSS。库是动态的,这意味着即使在加载页面后调整屏幕大小,它也会重置页脚的位置。我创建了这个库,因为CSS暂时解决了这个问题,但是当显示尺寸发生显着变化时,从桌面到平板电脑或反之亦然,它们要么重叠内容,要么不再保持粘性。

另一个解决方案是 CSS Media Queries,但您必须为不同尺寸的屏幕手动编写不同的 CSS 样式,而该库会自动完成其工作,并且受所有基本 JavaScript 支持浏览器的支持。

编辑CSS解决方案:

@media only screen and (min-height: 768px) {/* or height/length of body content including footer*/
    /* For mobile phones: */
    #footer {
        width: 100%;
        position:fixed;
        bottom:0;
    }
}

现在,如果显示的高度超过您的内容长度,我们会将页脚固定到底部,如果不是,它将自动出现在显示的最末尾,因为您需要滚动才能查看它。

而且,这似乎是比 JavaScript/库更好的解决方案。

之前我对本页上建议的解决方案没有任何运气,但最后,这个小技巧起作用了。我将把它作为另一种可能的解决方案。

footer {
  position: fixed;
  right: 0;
  bottom: 0;
  left: 0;
  padding: 1rem;
  background-color: #efefef;
  text-align: center;
}

弹性盒解决方案

对于自然的页眉和页脚高度,首选 Flex 布局。这个 Flex 解决方案在现代浏览器中进行了测试,并且在 IE11 中实际工作:)。

参见 JS 小提琴.

超文本标记语言

<body>
  <header>
    ...
  </header>
  <main>
    ...
  </main>
  <footer>
    ...
  </footer>
</body>  

CSS

html {
  height: 100%;
}

body {
  height: 100%;
  min-height: 100vh;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  margin: 0;
  display: flex;
  flex-direction: column;
}

main {
  flex-grow: 1;
  flex-shrink: 0;
}

header,
footer {
  flex: none;
}

对我来说,显示它(页脚)的最好方式是粘在底部但不始终覆盖内容:

#my_footer {
    position: static
    fixed; bottom: 0
}

jQuery 跨浏览器自定义插件 - $.footerBottom()

或者像我一样使用 jQuery,并将页脚高度设置为 auto 或者 fix, ,无论你喜欢什么,它都会起作用。该插件使用 jQuery 选择器,因此要使其工作,您必须将 jQuery 库包含到您的文件中。

这是运行插件的方法。导入jQuery,复制这个自定义jQuery插件的代码,导入jQuery后导入!它非常简单和基本,但很重要。

当你这样做时,你所要做的就是运行以下代码:

$.footerBottom({target:"footer"}); //as html5 tag <footer>.
// You can change it to your preferred "div" with for example class "footer" 
// by setting target to {target:"div.footer"}

无需将其放置在文档就绪事件中。它将按原样运行良好。当页面加载和窗口大小调整时,它将重新计算页脚的位置。

这是您不必理解的插件代码。只要知道如何实施即可。它会为你完成这项工作。但是,如果您想知道它是如何工作的,只需查看代码即可。我给你留下了评论。

//import jQuery library before this script

// Import jQuery library before this script

// Our custom jQuery Plugin
(function($) {
  $.footerBottom = function(options) { // Or use "$.fn.footerBottom" or "$.footerBottom" to call it globally directly from $.footerBottom();
    var defaults = {
      target: "footer",
      container: "html",
      innercontainer: "body",
      css: {
        footer: {
          position: "absolute",
          left: 0,
          bottom: 0,
        },

        html: {
          position: "relative",
          minHeight: "100%"
        }
      }
    };

    options = $.extend(defaults, options);

    // JUST SET SOME CSS DEFINED IN THE DEFAULTS SETTINGS ABOVE
    $(options.target).css({
      "position": options.css.footer.position,
      "left": options.css.footer.left,
      "bottom": options.css.footer.bottom,
    });

    $(options.container).css({
      "position": options.css.html.position,
      "min-height": options.css.html.minHeight,
    });

    function logic() {
      var footerOuterHeight = $(options.target).outerHeight(); // Get outer footer height
      $(options.innercontainer).css('padding-bottom', footerOuterHeight + "px"); // Set padding equal to footer height on body element
      $(options.target).css('height', footerOuterHeight + "!important"); // Set outerHeight of footer element to ... footer
      console.log("jQ custom plugin footerBottom runs"); // Display text in console so ou can check that it works in your browser. Delete it if you like.
    };

    // DEFINE WHEN TO RUN FUNCTION
    $(window).on('load resize', function() { // Run on page loaded and on window resized
      logic();
    });

    // RETURN OBJECT FOR CHAINING IF NEEDED - IF NOT DELETE
    // return this.each(function() {
    //   this.checked = true;
    // });
    // return this;
  };
})(jQuery); // End of plugin


// USE EXAMPLE
$.footerBottom(); // Run our plugin with all default settings for HTML5
/* Set your footer CSS to what ever you like it will work anyway */
footer {
  box-sizing: border-box;
  height: auto;
  width: 100%;
  padding: 30px 0;
  background-color: black;
  color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<!-- The structure doesn't matter much, you will always have html and body tag, so just make sure to point to your footer as needed if you use html5, as it should just do nothing run plugin with no settings it will work by default with the <footer> html5 tag -->
<body>
  <div class="content">
  <header>
    <nav>
      <ul>
        <li>link</li>
        <li>link</li>
        <li>link</li>
        <li>link</li>
        <li>link</li>
        <li>link</li>
      </ul>
    </nav>
  </header>

  <section>
      <p></p>
      <p>Lorem ipsum...</p>
    </section>
  </div>
  <footer>
    <p>Copyright 2009 Your name</p>
    <p>Copyright 2009 Your name</p>
    <p>Copyright 2009 Your name</p>
  </footer>

Flex 解决方案对我来说很有效,可以使页脚具有粘性,但不幸的是,将正文更改为使用 Flex 布局会使我们的一些页面布局发生变化,而且效果并没有变得更好。最终对我有用的是:

    jQuery(document).ready(function() {

    var fht = jQuery('footer').outerHeight(true);
    jQuery('main').css('min-height', "calc(92vh - " + fht + "px)");

});

我从 ctf0 的回复中得到了这个 https://css-tricks.com/ Couple-takes-sticky-footer/

自从 网格 解决方案还没有提出,就在这里,只有两个 声明 为了 父元素, ,如果我们取 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>

这些项目沿横轴均匀分布在对齐容器中。每对相邻项目之间的间距是相同的。第一个项目是与主要启动边缘的冲洗,最后一项是与主端边缘冲洗。

      div.fixed {
        position: fixed;
        bottom: 0;
        right: 0;
        width: 100%;
        border: 3px solid #73AD21;
      }
  <body style="height:1500px">

    <h2>position: fixed;</h2>

    <p>An element with position: fixed; is positioned relative to the viewport, which means it always stays in the same place even if the page is scrolled:</p>

    <div class="fixed">
      This div element has position: fixed;
    </div>

  </body>

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top