移动开发中固定布局

4次阅读

共计 1025 个字符,预计需要花费 3 分钟才能阅读完成。

记录一下移动开发过程中出现的问题。从最常见的布局说起,固定头部或底部算是最常见的需求了假定页面布局如下:
<body>
<div class=”header”></div>
<div class=”main”></div>
<div class=”footer”></div>
</body>

实现头部、底部固定,中间滚动,有三种简单实现方式:

fixed 布局
absolute 布局
flex 布局

先从最简单的 fixed 布局开始,实现方式如下:
html, body {
overflow: hidden;
height: 100%;
}
.header, .footer {
position: fixed;
left: 0;
height: 50px;
}
.header {
top: 0;
}
.footer {
bottom: 0;
}
.main {
height: 100%;
padding: 50px 0;
}
这种布局在大多数情况下是正常显示的,但在移动端上(iOS)position: fixed 失效,会有所谓的兼容性问题;

第二种方式 absolute 实现如下:
html, body {
position: relative;
height: 100%;
}
.header, .footer {
position: absolute;
left: 0;
width: 100%;
height: 50px;
}
.header {
top: 0;
}
.footer {
bottom: 0;
}
.main {
height: 100%;
width: 100%;
padding: 50px 0;
overflow: auto;
}
这种方式在移动端(iOS)上能准确布局

第三种方式 flex 布局如下:
body {
height: 100%;
display: flex;
flex-direction: column;
}
.header, .footer {
height: 50px;
}
.main {
flex: 1;
overflow: auto;
-webkit-overflow-scrolling: touch; /*ios 滚动流畅 */
}
flex 定位在移动端兼容到了 iOS 7.1+,Android 4.4+, 在 iOS3.2~ios6.0 可兼容 flexbox,如果使用 autoprefixer 等工具还可以降级为旧版本的 flexbox,可以兼容到 iOS 3.2 和 Android 2.1。

若是涉及到移动开发布局中碰到固定某一部分,其余部分可滚动,尽量不要使用 position: fixed, 可用 absolute 替代,若是不需要考虑兼容性,用 flex 更佳。

正文完
 0