固定定位實現(xiàn)上下欄布局
1. 前言
上下欄通常是一直存在在屏幕上,將上下欄固定在屏幕的特定位置,然后為內(nèi)容添加合適的邊距。
一聽到要把什么東西固定在屏幕上的話,那么第一時間腦海里反應(yīng)出來的應(yīng)該就是固定定位。
2. 實現(xiàn)
將上欄以及下欄固定在屏幕的特定位置,然后主盒子添加合適的上下邊距:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- 在這里用link標簽引入中文漸變色 -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/chinese-gradient">
<style>
/* 清除默認樣式 */
* { padding: 0; margin: 0; }
/* 令html和body全屏顯示 */
html, body { height: 100% }
/* 設(shè)置父元素為相對定位 */
body { position: relative; }
/* 上面的那欄 */
.top {
/* 設(shè)置為固定定位 */
position: fixed;
/* 距離上邊左邊為0 */
top: 0;
left: 0;
/* 寬度鋪滿屏幕 */
width: 100%;
/* 給個合適的高度 */
height: 80px;
/* 綠色背景 */
background: var(--極光綠);
}
.main {
/* 給個合適的上下邊距 */
margin: 90px 0;
/* 給個合適的高度 */
height: 1000px;
/* 漸變背景 */
background: var(--燈紅酒綠);
}
/* 下面的那欄 */
.bottom {
/* 設(shè)置為固定定位 */
position: fixed;
/* 距離下邊左邊為0 */
bottom: 0;
left: 0;
/* 寬度鋪滿屏幕 */
width: 100%;
/* 給個合適的高度 */
height: 80px;
/* 黃色背景 */
background: var(--芒果黃);
}
div {
/* 白色文字 */
color: white;
/* 字體大小 */
font-size: 30px
}
</style>
</head>
<body>
<div class="top">無論你怎么滑動屏幕,我都是固定不變的</div>
<div class="main">
主盒子頂部
</div>
<div class="bottom">無論你怎么滑動屏幕,我都是固定不變的</div>
</body>
</html>
運行結(jié)果:
3. 小結(jié)
大家在做這個案例的時候最好在元素內(nèi)寫上一些文字或者填充一些漸變色來獲得更清晰的顯示效果。
下一小節(jié)我們來講講為什么要在中間的 DOM 元素上寫一個上下邊距。