Double scroll bar
这几天有个非常annoying的问题,一个网页布局乱套了。原因是一个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 的结合),这个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,
// 内容高度超过父容器
border: 4px solid #f0c;
}
解决方法:
- 去掉最外面
body
的100%,但会影响到另外的页面,需要double scroll bar的那个页面变超丑。 - 也加一个auto,向double scroll bar妥协。
为啥设了height百分比,但是它不生效
经常看到有人问,为啥我设立height百分比,但是它还是不生效呢,先要说,你要的效果是个啥效果。比如这个code,当我把最外层的body上的height:100%
去掉,惊奇的发现.container
的height: 50%;
不能为非作歹了,它的高度完全和子元素的高度一致。
html, body {
margin: 0px;
}
.container {
height: 50%; // 没用
border:5px solid #68c;
.sub_container {
height: 2600px; // 最里面的子元素高度明显大于 viewport height,
// 内容高度超过父容器,.container被撑大到2600px
border: 4px solid #f0c;
}
html, body {
margin: 0px;
}
.container {
height: 50%; // 没用
border:5px solid #68c;
.sub_container {
height: 60px; // 内容高度明显小于50% viewport,
// .container高度也只有60px
border: 4px solid #f0c;
}
这是因为在使用height百分比的时候,它本身就是一个相对的量,首先需要自己的老爸有一个具体的高度,否则只能看子敬父,儿子多大它多大。
教训
据说这个100%在不同的浏览器上解释也不同,我还没有考证过,另外,大家合作布局的时候,注意下这个坑爹货。