当内容足够多可以撑开底部到达浏览器的底部,如果内容不够多,不足以撑开元素到达浏览器的底部时,就要解决如何使元素粘住浏览器底部。让一个Footer元素如何粘住底部,使其无论内容多或者少,Footer元素始终紧靠在浏览器的底部。" u- R3 C' k! t- p
方法一:全局增加一个负值下边距等于底部高度
( |) p3 F9 \7 D+ ?7 g 有一个全局的元素包含除了底部之外的所有内容。它有一个负值下边距等于底部的高度。
9 `# x, q$ q- Z/ v! H6 e3 u html代码:
; d' ]; k# D% F X <body>
<div class="wrapper">
content
<div class="push"></div>
</div>
<footer class="footer"></footer>
</body> css代码:. r% G. w! W1 {5 e) m1 ^
html, body {
height: 100%;
margin: 0;
}
.wrapper {
min-height: 100%;
/* Equal to height of footer */
/* But also accounting for potential margin-bottom of last child */
margin-bottom: -50px;
}
.footer,
.push {
height: 50px;
} 这个代码需要一个额外的元素.push等于底部的高度,来防止内容覆盖到底部的元素。这个push元素是智能的,它并没有占用到底部的利用,而是通过全局加了一个负边距来填充。
4 m" F$ c* s2 i; y% h R, i; j 方法二:底部元素增加负值上边距 4 E9 [4 {& k; Z/ j; b ~
虽然这个代码减少了一个.push的元素,但还是需要增加多一层的元素包裹内容,并给他一个内边距使其等于底部的高度,防止内容覆盖到底部的内容。
( r3 h2 I/ z* k" Z HTML代码:/ t/ q* A+ |1 n. ?; a
<body>
<div class="content">
<div class="content-inside">
content
</div>
</div>
<footer class="footer"></footer>
</body> CSS:html, body {
height: 100%;
margin: 0;
}
.content {
min-height: 100%;
}
.content-inside {
padding: 20px;
padding-bottom: 50px;
}
.footer {
height: 50px;
margin-top: -50px;
}方法三:使用calc()计算内容的高度
4 n$ |; c( B2 F) m8 b6 }3 C HTML:
( k' [4 A L1 h3 s1 V
7 I+ M0 J1 w. I& ?" n0 U3 D( V" Q <body>
<div class="content">
content
</div>
<footer class="footer"></footer>
</body> CSS:
. O+ L0 O1 k$ h3 V" s* W. K, u .content {
min-height: calc(100vh - 70px);
}
.footer {
height: 50px;
} 给70px而不是50px是为了为了跟底部隔开20px,防止紧靠在一起。, U2 R- ~2 } H3 {6 J& y% U
方法四:使用flexbox
5 G0 ~( y3 _" n% h3 z9 d% }6 l HTML:
! _% t# }6 B- Q% {. D5 v8 s 2 K1 B; m# g* h" C/ L# T9 Z
<body>
<div class="content">
content
</div>
<footer class="footer"></footer>
</body> CSS:
# v+ Y$ r4 n' S4 U html {
height: 100%;
}
body {
min-height: 100%;
display: flex;
flex-direction: column;
}
.content {
flex: 1;
}方法五:使用grid布局 " R8 n M7 E) l8 J7 a) R; P
HTML:' G7 X1 S! ^" K" u; ]1 l) H- ]" Z
8 Z" k; u5 A t# |$ r <body>
<div class="content">
content
</div>
<footer class="footer"></footer>
</body> CSS:
4 ~: I6 q. m6 f0 s& U$ A* { html {
height: 100%;
}
body {
min-height: 100%;
display: grid;
grid-template-rows: 1fr auto;
}
.footer {
grid-row-start: 2;
grid-row-end: 3;
} grid早于flexbox出现,但并没有flexbox被广泛支持,你可能在chrome Canary或者Firefox开发版上才可以看见效果。