我有一个简单的2列布局,带有一个脚注,可以清除标记中的左右div。我的问题是,我不能让页脚留在所有浏览器的页面底部。如果内容向下推页脚,它就会起作用,但情况并不总是如此。
当前回答
查看http://1linelayouts.glitch.me/,示例4。Una Kravets解决了这个问题。
这将创建一个带有页眉、主页和页脚的3层页面。
-你的页脚将始终停留在底部,并使用空间来适应内容;
-你的标题将始终保持在顶部,并使用空间来适应内容
-你的主系统总是会使用所有可用的剩余空间(剩余的部分空间),如果需要,足够填满整个屏幕。
HTML
<div class="parent">
<header class="blue section" contenteditable>Header</header>
<main class="coral section" contenteditable>Main</main>
<footer class="purple section" contenteditable>Footer Content</footer>
</div>
CSS
.parent {
display: grid;
height: 95vh; /* no scroll bars if few content */
grid-template-rows: auto 1fr auto;
}
其他回答
一个快速简单的解决方案,使用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 > © Copyright 2021</p> </div> </footer> </body>
如果你不希望它使用位置固定,并在移动设备上烦人地跟随你,这似乎对我来说是有效的。
html {
min-height: 100%;
position: relative;
}
#site-footer {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
padding: 6px 2px;
background: #32383e;
}
只需要将html设置为min-height: 100%;位置是相对的,位置是绝对的;底部:0;左:0;在页脚。然后确保页脚是主体中的最后一个元素。
如果这对其他人不起作用,请告诉我,以及为什么。我知道这些乏味的风格技巧在我没有想到的各种情况下会表现得很奇怪。
对于这个问题,我看到的许多答案都是笨拙的,难以实现和低效的,所以我想我应该尝试一下,并提出我自己的解决方案,只是一点点css和html
超文本标记语言 身体{ 高度:100%; 保证金:0; } .body { Min-height: calc(100% - 2rem); 宽度:100%; 背景颜色:灰色; } .footer { 高度:2快速眼动; 宽度:100%; 背景颜色:黄色; } 身体< > <div class="body">test as body</div> <div class="footer">test as footer</div> 身体< / >
这是通过设置页脚的高度,然后使用CSS计算出页面的最小高度,页脚仍然在底部,希望这有助于一些人:)
设置#页脚的CSS为:
position: absolute;
bottom: 0;
然后,您需要在#边栏和#内容的底部添加填充或边距,以匹配#footer的高度,或者当它们重叠时,#footer将覆盖它们。
此外,如果我没记错的话,IE6在底部有一个问题:0 CSS。你可能不得不为IE6使用JS解决方案(如果你关心IE6的话)。
react友好的解决方案-(不需要分隔符div)
Chris coyer(值得尊敬的CSS-Tricks网站)在sticky - footer上保持了最新的页面,现在至少有五种创建sticky footer的方法,包括使用FlexBox和CSS-Grid。
为什么这很重要?因为,对我来说,我多年来使用的早期/旧方法对React不起作用——我不得不使用Chris的flexbox解决方案——这很简单,也很有效。
下面是他的CSS-Tricks flexbox粘性页脚-看看下面的代码,它不可能更简单。
(下面的StackSnippet示例没有完美地呈现示例的底部。页脚会延伸到屏幕底部,这在现实生活中是不会发生的。)
html,身体{高度:100%;} 身体{显示:flex;flex-direction:列;} .content {flex: 1 0 auto;} /* flex:增长/收缩/伸缩基础;* / .footer {flex-shrink: 0;} /* ----以下仅为演示---- */ .footer{背景:苍绿色;} 身体< > <div class="content">Page content - height扩展到填充空间</div> <footer class="footer"> footer Content</footer> . 身体< / >
Chris还为那些喜欢网格的人演示了这个CSS-Grid解决方案。
引用:
CSS-Tricks - Flexbox的完整指南