ios下overflow:hidden 無效原因及解決方案
在ipad和ios上設置overflow:hidden
不起作用,目前網上找到的方法是給父級元素添加position:fixed
,比如這樣:
body { height: 100%; overflow: hidden; width: 100%; position: fixed; }
原因暫時還沒想清楚,網上也沒有針對這方面的具體解釋,等找到了回頭來更新
在Stack Overflow上找到了大概的原因,翻譯如下:
overflow的實現原理:
-
整個
viewport
的overflow
是由html
中的overflow
來決定的; -
假如你不去設置
html
的overflow
(也就是默認的visible
屬性),而去設置body
的overflow:hidden
,也是可以的; -
假如你設置了
html
的overflow
屬性的值(除去默認的visible
),那么body
的overflow
屬性就不會生效了/*body的overflow設置無效*/ html{overflow: hidden;} body{overflow: scroll;}
上面的幾點在大部分的現代瀏覽器里都是成立的,但ios下的除外,包括iphone和ipad
ios認為(瑪德,標准制定者就是任性),網頁內容是個整體,需要將所有的都顯示出來,所有overflow
就不該起作用,這是他們刻意的,不是bug,而且在更高版本的ios7,8,9中也是這樣設定的(mmp).
對viewport我們沒法改變,但是我們可以通過改變body自身的overflow:
- 改變html的overflow默認屬性(
visible
)為auto
或者hidden
,哪個都行,對后面的效果都是一致的,這樣body就不會繼承viewport的overflow屬性,然后通過設置body的overflow:hidden
,大部分的溢出內容就會被隱藏掉 - 不過設置了
position:absolute
的除外,因為它默認是相對viewport進行絕對定位的,這個時候你要對body進行設置position:relative
總結起來一句話,body的范圍要比viewport的范圍要大,這樣才能使body的overflow生效
達到這個效果:
- body需要設置viewport的寬高:
body{width:100%;height:100%}
- html和body的padding,margin都不能有;html的border也不能有
- 給body加上
box-sizing: border-box
,解決padding的問題(這里沒咋看懂,把原文貼一下:Finally, in order to deal with body padding, and in case you ever want to set a border on the body, make the math work with box-sizing: border-box for the body.)
最后的代碼整理如下:
html { overflow: hidden; height: 100%; margin: 0; padding: 0; border: none; } body { overflow: hidden; position: relative; box-sizing: border-box; margin: 0; height: 100%; }