Double scroll bar
這幾天有個非常annoying的問題,一個網(wǎng)頁布局亂套了。原因是一個slightly problem height:100%
。
這個height:100%
寫在了body
和html
tag上面。在他們的第一個直系子孫Div上面也有一個100%,借此達到了double scroll bar的效果。代碼模擬情況如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Set DIV Height to 100% Using CSS</title>
<style type="text/css">
html, body {
height: 100%;
margin: 0px;
}
.container {
height: 100%;
border:5px solid #68c;
overflow:auto //Put overflow auto, there will be a double scroll bar
.sub_container {
height: 2600px; //最里面的子元素高度明顯大于 viewport height
border: 4px solid #f0c;
}
</style>
</head>
<body>
<div class="container">The height of this DIV element is equal to the
100% height of its parent element's height.
<div class="sub_container">
here is a test
</div>
</div>
</body>
</html>
子元素固定高度超過height 100%
因為是single page application,幾個不同的頁面實際render時共享一個父容器,而另一個頁面又是需要子元素固定高度的,1200px
,當然這并不是問題,問題是,頁面上有個footer是由template來提供的(django 和 react 的結(jié)合),這個footer在我所render的父容器外面,自然,緊鄰著.container
。于是它就神一般的飄到了子div(.sub_container)的下面。
html, body {
height: 100%;
margin: 0px;
}
.container {
height: 90%;
border:5px solid #68c;
.sub_container {
height: 2600px; // 最里面的子元素高度明顯大于 viewport height,
// 內(nèi)容高度超過父容器
border: 4px solid #f0c;
}
解決方法:
- 去掉最外面
body
的100%,但會影響到另外的頁面,需要double scroll bar的那個頁面變超丑。 - 也加一個auto,向double scroll bar妥協(xié)。
為啥設了height百分比,但是它不生效
經(jīng)常看到有人問,為啥我設立height百分比,但是它還是不生效呢,先要說,你要的效果是個啥效果。比如這個code,當我把最外層的body上的height:100%
去掉,驚奇的發(fā)現(xiàn).container
的height: 50%;
不能為非作歹了,它的高度完全和子元素的高度一致。
html, body {
margin: 0px;
}
.container {
height: 50%; // 沒用
border:5px solid #68c;
.sub_container {
height: 2600px; // 最里面的子元素高度明顯大于 viewport height,
// 內(nèi)容高度超過父容器,.container被撐大到2600px
border: 4px solid #f0c;
}
html, body {
margin: 0px;
}
.container {
height: 50%; // 沒用
border:5px solid #68c;
.sub_container {
height: 60px; // 內(nèi)容高度明顯小于50% viewport,
// .container高度也只有60px
border: 4px solid #f0c;
}
這是因為在使用height百分比的時候,它本身就是一個相對的量,首先需要自己的老爸有一個具體的高度,否則只能看子敬父,兒子多大它多大。
教訓
據(jù)說這個100%在不同的瀏覽器上解釋也不同,我還沒有考證過,另外,大家合作布局的時候,注意下這個坑爹貨。