如何使用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 分享