記錄一下移動開發過程當中出現的問題。
從最多見的佈局提及,固定頭部或底部算是最多見的需求了
假定頁面佈局以下:css
<body> <div class="header"></div> <div class="main"></div> <div class="footer"></div> </body>
實現頭部、底部固定,中間滾動,有三種簡單實現方式:html
先從最簡單的fixed佈局開始,實現方式以下:ios
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
失效,會有所謂的兼容性問題;web
第二種方式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佈局以下: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。flexbox
如果涉及到移動開發佈局中碰到固定某一部分,其他部分可滾動,儘可能不要使用position: fixed
,可用absolute
替代,如果不須要考慮兼容性,用flex更佳。code