在移動web中使用position:fixed,會踩到不少坑,在我以前的一篇文章《移動端web頁面使用position:fixed問題總結》中已經總結了不少bug,可是在後續的開發中有關fixed的未知bug愈來愈多,我也在儘可能的尋找解決方案。android
這篇文章就來先解決一個坑,fixed元素的寬度自適應。ios
當橫屏時,fixed元素不能自適應橫屏的寬度,bug表現以下:git
這個bug主要在android自帶瀏覽器下出現,與手機型號和系統版本無關,幾乎全部android都沒法倖免,在不一樣的手機下可能表現會有一點點差別,但都是一樣的bug。github
致使bug的緣由我不清楚,若有高人請指點。web
下面這個解決方案在12款主流手機上測試經過(三星、小米、魅族、華爲、中心等),若是還未徹底解決能夠回覆這篇文章。瀏覽器
解決問題的關鍵就是:fixed元素內部必須嵌套一個position:absolute
元素,用來裝載內容,目的就是爲了讓內容脫離fixed文檔流,屏蔽一些fixed的坑移動端web
別問我爲何,我也不知道爲何,可是這樣寫居然神奇的好使了,若有高人請指點迷津。佈局
我在下面的例子中聲明瞭兩種最經常使用的fixed元素:header和footer測試
position fixed headerflex
header中我使用了float來定位左右兩邊的icon。右側icon必定不能使用position:absolute
定位,若是使用了absolute,在一些android自帶瀏覽器下橫屏時,右側icon沒法自適應到右側,會出現與上面第二幅圖中差很少的bug。
<header> <div class="fixed"> <div class="wrap float"> <div class="left-icon"> <span class="glyphicon glyphicon-chevron-left"></span> </div> <h1>HEADER</h1> <div class="right-icon"> <span class="glyphicon glyphicon-calendar"></span><span class="glyphicon glyphicon-list"></span> </div> </div> </div> </header>
position fixed footer
footer中是一個flex的佈局,'display:flex'容器必定不要直接聲明到fixed元素下,必須使用'position:absolute'容器包裝一層。
<footer> <div class="fixed"> <div class="wrap flex"> <a href="#"><span class="glyphicon glyphicon-picture"></span></a> <a href="#"><span class="glyphicon glyphicon-film"></span></a> <a href="#"><span class="glyphicon glyphicon-qrcode"></span></a> </div> </div> </footer>
解決方案DEMO:http://jsbin.com/omaCOSir/latest
題外話
一個placeholder自適應bug,頁面中使用<input>
標籤而且有屬性placeholder
,在頁面橫屏再轉回豎屏時,會致使頁面沒法自適應,不管是android仍是ios都會中招。
解決方法是,在<input>
外層容器中加overflow:hidden
,這個bug我沒有截圖,你們能夠自測。
轉自:https://github.com/maxzhang/maxzhang.github.com/issues/11