通常在頁面中,需要使頁腳 footer 部分始終處於底部。當頁面高度不夠 100% 時, footer 處於頁面最底部,當頁面內容高於 100% 時,頁腳元素可以被撐到最底部。
方法一:絕對定位
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>旋轉六面體動畫</title>
<style>
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
html {
height: 100%
}
/* 這里footer的父元素為 body, 實際應用中,不一定要以body為父元素,只要確保footer的父元素的最小高度為100%就行 */
body {
position: relative;
min-height: 100%;
padding: 0;
padding-bottom: 40px;
}
#footer {
height: 40px;
background: #eee;
width: 100%;
position: absolute;
bottom: 0;
}
</style>
</head>
<body>
<div class="box">
<h1>content</h1>
<h1>content</h1>
<h1>content</h1>
<h1>content</h1>
<h1>content</h1>
</div>
<footer id="footer">
<p>footer footer footer</p>
</footer>
</body>
</html>
方法二: flex 布局
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>footer</title>
<style>
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
html {
height: 100%
}
body {
height: 100%;
display: flex;
flex-direction: column;
}
#header {
height: 40px;
background: red;
flex: 0 0 auto;
}
#box {
background: #eee;
flex: 1 0 auto;
}
#footer {
height: 40px;
background: rgb(129, 129, 201);
flex: 0 0 auto;
}
</style>
</head>
<body>
<header id="header">
header header header
</header>
<div id="box">
<h1>content</h1>
<h1>content</h1>
<h1>content</h1>
<h1>content</h1>
<h1>content</h1>
</div>
<footer id="footer">
<p>footer footer footer</p>
</footer>
</body>
</html>