我的基本布局很简单:
header {
background: red;
}
main {
background: aqua;
font-size: 48px;
}
footer {
background: grey;
position: fixed;
bottom: 0;
width: 100%;
padding: 20px;
}Run Code Online (Sandbox Code Playgroud)
<header>head</header>
<main>
Curabitur aliquam convallis luctus. Vestibulum dolor turpis, consectetur a placerat eget, pellentesque id eros. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.
</main>
<footer>foot</footer>Run Code Online (Sandbox Code Playgroud)
如果我制作我的页脚,position:fixed它确实会留在页面底部,但是在需要滚动时它是一个“粘性”页脚和覆盖的内容。
我想将页脚保留在底部,但不是fixed.
这甚至可以用纯 CSS 来实现吗?
G-C*_*Cyr 10
如今,flex 或 grid 可以轻松完成:
body {
margin: 0;
min-height: 100vh;
display: grid;
grid-template-rows: auto 1fr auto;
}
body>* {
padding: 0.5em;
border: solid;
margin: 2px;
}
/* does it push footer down if too tall */
main:hover {
padding-bottom: 100%;
}Run Code Online (Sandbox Code Playgroud)
<header>header</header>
<main>main</main>
<footer>footer</footer>Run Code Online (Sandbox Code Playgroud)
body {
margin: 0;
min-height: 100vh;
display: flex;
flex-flow: column;
}
main {
flex-grow: 1;
}
body>* {
padding: 0.5em;
border: solid;
margin: 2px;
}
/* does it push footer down if too tall */
main:hover {
padding-bottom: 100%;
}Run Code Online (Sandbox Code Playgroud)
<header>header</header>
<main>main</main>
<footer>footer</footer>Run Code Online (Sandbox Code Playgroud)
对于任何好奇或喜欢旧时代的人display:table/table-row (仅当您的浏览器不支持flex和/或在使用另一种方法或grid时不知道页脚大小时才使用)floatposition:
body {
margin: 0;
height: 100vh;
width: 100%;
table-layout: fixed;
display: table;
border-spacing: 2px;
}
header > div,
footer > div {
height: 0; /* will grow like a table*/
}
body>* {
display: table-row;
}
body>*>div {
display: table-cell;
padding: 0.5em;
border: solid;
margin: 2px;
}
/* does it push footer down if too tall */
main:hover > div {
padding-bottom: 100%;
}Run Code Online (Sandbox Code Playgroud)
<header>
<div>header</div>
</header>
<main>
<div>main</div>
</main>
<footer>
<div>footer</div>
</footer>Run Code Online (Sandbox Code Playgroud)
有position:absolute;。这是一个 CSS 属性,允许您控制任何元素的确切位置。例如:
<style>
footer {
position:absolute;
top:(numberofuntits)px;
left: (numberofUnits)px;
}
</style>
Run Code Online (Sandbox Code Playgroud)
这使得无论页面发生什么情况,它都会保持在原位,有点像固定的,只是更具体。虽然我认为您真正需要的是position:relative;所以它会相对于页面上的其他元素调整页脚。为了整合这一点,我添加了一些其他有用的样式,您可能需要考虑添加...(可以在 www.w3schools.com 上找到这些样式)我希望这是您所需要的:
<style>
footer {
clear: both; //prevents floating elements from right/left of footer
position: relative; //Positions footer relative to other elements on hte page
z-index: 1; //z-index positions elements in front or behind eachother, most have a //natual z-index of -1
height: -3em; //exactly what it says...
margin-top: 40em; //moves footer to bottom of all elements
}
</style>
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!