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


当前回答

一个快速简单的解决方案,使用flex

将html和body的高度设置为100%

html,
body {
  width: 100%;
  height: 100%;
}

将主体显示为具有列方向的flex:

body { 
  min-height: 100%;
  display: flex;
  flex-direction: column;
}

为main添加flex-grow: 1

main {
  flex-grow: 1;
}

flex-grow指定应将伸缩容器中剩余空间的多少分配给项(伸缩增长因子)。

*, *::after, *::before{ margin: 0; padding: 0; box-sizing: border-box; } html, body { width: 100%; height: 100%; } body { min-height: 100%; display: flex; flex-direction: column; } main { flex-grow: 1; } footer{ background-color: black; color: white; padding: 1rem 0; display: flex; justify-content: center; align-items: center; } <body> <main> <section > Hero </section> </main> <footer > <div> <p > &copy; Copyright 2021</p> </div> </footer> </body>

其他回答

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%的上距,那么这个方法应该是有用的。

我创建了一个非常简单的库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媒体查询,但你必须为不同大小的屏幕手动编写不同的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/库更好的解决方案。

要获得一个粘性页脚:

为你的内容设置一个<div> with class="wrapper"。 在包装器的</div>结束之前放置 < div class = "推" > < / div >。 在包装器的</div>结束后放置 < div class = "脚注" > < / 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 */
}

下面是一个使用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 )

尝试在内容和侧栏周围放置容器div(带有overflow:auto)。

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