当内容足够多可以撑开底部到达浏览器的底部,如果内容不够多,不足以撑开元素到达浏览器的底部时,就要解决如何使元素粘住浏览器底部。让一个Footer元素如何粘住底部,使其无论内容多或者少,Footer元素始终紧靠在浏览器的底部。# D0 \0 Q& x+ p2 X5 v' G
方法一:全局增加一个负值下边距等于底部高度
' O7 X- ?$ N& P s+ M7 ?5 u" [; { 有一个全局的元素包含除了底部之外的所有内容。它有一个负值下边距等于底部的高度。
. B$ ~3 d E9 l" M1 A1 I( M html代码:
) t: l8 p0 g8 f9 C" q+ z- K$ f <body>
<div class="wrapper">
content
<div class="push"></div>
</div>
<footer class="footer"></footer>
</body> css代码:- H; Z; W3 f5 ]
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元素是智能的,它并没有占用到底部的利用,而是通过全局加了一个负边距来填充。
1 e G i @5 }& h 方法二:底部元素增加负值上边距
9 A2 _. l/ t! { 虽然这个代码减少了一个.push的元素,但还是需要增加多一层的元素包裹内容,并给他一个内边距使其等于底部的高度,防止内容覆盖到底部的内容。 7 l. z/ ^6 b2 \# C3 F: {
HTML代码: O: v. K7 i/ k6 x8 Y3 {5 H& ~
<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()计算内容的高度 3 ]" `! R. u; ~( |$ }* F3 t& q4 ?
HTML:
8 v# F9 E9 y, l1 b& b* N; }) }
2 V B. g, G3 z9 ^+ y; L; a. q# T j <body>
<div class="content">
content
</div>
<footer class="footer"></footer>
</body> CSS:
b- R2 d! F0 V( v6 h .content {
min-height: calc(100vh - 70px);
}
.footer {
height: 50px;
} 给70px而不是50px是为了为了跟底部隔开20px,防止紧靠在一起。/ {# X' U! e; h( d: P; G" y/ p6 \
方法四:使用flexbox d8 y/ J# G# ^( H1 N# k& \7 V
HTML:
, z5 O. A$ T& ~9 E2 @( r , N! B7 r" [) O7 G3 L# c( o$ m5 |
<body>
<div class="content">
content
</div>
<footer class="footer"></footer>
</body> CSS:
- B1 K1 L7 [) u5 Z8 z' c html {
height: 100%;
}
body {
min-height: 100%;
display: flex;
flex-direction: column;
}
.content {
flex: 1;
}方法五:使用grid布局 1 ^* f7 p. |- n1 g$ ], [9 f
HTML:
/ o% q) t. Z* o8 v4 H( y/ Q& y
3 S' F S& K& g1 t" e <body>
<div class="content">
content
</div>
<footer class="footer"></footer>
</body> CSS:. }0 y4 G6 M5 f. f8 t6 E' I( U) _
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开发版上才可以看见效果。