如何使用CSS在移動頁面中實現固定頭部和頁腳以及可滾動內容區的布局?

如何使用CSS在移動頁面中實現固定頭部和頁腳以及可滾動內容區的布局?

移動端頁面:固定頭部、底部及可滾動內容區的css布局方案

移動端開發中,常見需求是:頁面頭部和底部固定,中間內容區域可上下滾動。本文將介紹幾種css布局方法來實現此效果。 假設html結構包含頭部(.head)、內容區(.content)和頁腳(.foot)三個部分。

解決方案

1. position: fixed; 固定定位

此方法利用固定定位固定頭部和底部,內容區則可滾動。

html, body {   height: 100%;   margin: 0;   padding: 0; }  body {   display: flex;   flex-direction: column; }  .head {   position: fixed;   top: 0;   left: 0;   right: 0;   z-index: 1000; /* 確保頭部在內容之上 */   background-color: #f8f8f8;   padding: 10px; }  .content {   flex: 1; /* 占據剩余空間 */   overflow-y: auto;   padding-top: 50px; /* 考慮頭部高度 */   padding-bottom: 50px; /* 考慮底部高度 */ }  .foot {   position: fixed;   bottom: 0;   left: 0;   right: 0;   z-index: 1000; /* 確保底部在內容之上 */   background-color: #f8f8f8;   padding: 10px; }

.head 和 .foot 使用 position: fixed; 固定,z-index 保證其在內容之上。.content 使用 flex: 1; 占據剩余空間,overflow-y: auto; 實現滾動。padding-top 和 padding-bottom 避免內容被頭部和底部遮擋。

2. Flexbox 彈性盒子布局法

Flexbox 也能輕松實現此布局。

立即學習前端免費學習筆記(深入)”;

html, body {   height: 100%;   margin: 0;   padding: 0; }  body {   display: flex;   flex-direction: column; }  .head {   flex-shrink: 0; /* 防止頭部收縮 */   height: 50px; /* 固定頭部高度 */   background-color: #f8f8f8;   padding: 10px; }  .content {   flex: 1; /* 占據剩余空間 */   overflow-y: auto;   background-color: #ffffff; }  .foot {   flex-shrink: 0; /* 防止底部收縮 */   height: 50px; /* 固定底部高度 */   background-color: #f8f8f8;   padding: 10px; }

頭部和底部使用 flex-shrink: 0; 防止其收縮,height 屬性設置固定高度。.content 使用 flex: 1; 占據剩余空間,并設置滾動。

3. Grid 網格布局法

Grid 布局同樣適用。

html, body {   height: 100%;   margin: 0;   padding: 0; }  body {   display: grid;   grid-template-rows: 50px 1fr 50px; /* 定義頭部、內容區、底部高度 */ }  .head {   background-color: #f8f8f8;   padding: 10px; }  .content {   overflow-y: auto;   background-color: #ffffff; }  .foot {   background-color: #f8f8f8;   padding: 10px; }

grid-template-rows 直接定義了頭部、內容區和底部的行高,1fr 表示內容區占據剩余空間。.content 設置滾動。

以上三種方法都能實現目標布局,選擇哪種方法取決于個人偏好和項目需求。 記得根據實際情況調整頭部和底部的高度以及樣式。

? 版權聲明
THE END
喜歡就支持一下吧
點贊14 分享