在学习页面布局的时候,特别是浮动,遇到了一些不可预知的情况。
<body>
<div id="header"><h1>Header Content</h1></div>
<div id="page">
<div class="main"><h1>Main Content</h1></div>
<div class="sidebar"><h1>Sidebar Content</h1></div>
</div>
<div id="footer"><h1>Footer Content</h1></div>
</body>
页面结构是一个头部header,中间是内容页page,其中page页有两大板块,分别使用了左右浮动,底部是footer,可是使用如下样式,并没有达到预期的样子。
css代码如下:
<style type="text/css">
h1 {
font-size: 20px;
margin: 0;
color: #fff;
}
#page {
margin-bottom: 20px;
}
/* #page:after,#page:before{
content: "";
display: table;
} */
/* #page:after{
clear:both;
overflow: hidden;
} */
#header{
width:100%;
background-color: green;
margin-bottom: 10px;
padding: 20px;
}
.main{
background: orange;
float: left;
padding: 20px;
width:60%;
}
.sidebar{
background-color: #f36;
float: right;
width: 38%;
padding: 20px;
}
#footer{
width:100%;
background: #36f;
padding: 20px;
clear: both;
}
</style>
页面发现page的margin-bottom不取效果,如下:
而且左右浮动宽度60%+38%=98%没有超过100%,但是在显示上就换行了。
其中footer中加入了clear:both来清除浮动,如果没有加这一句,footer面板的div将顶在上面。
同理把main 和sidebar使用page进行包裹,是不是浮动还进行了传递,使得跟下面的footer间的margin-bottom不取作用呢??
我尝试在page中加入clear:both,page的margin-bottom还是没有效果。
#page {
margin-bottom: 20px;
/*clear:both;*/
}
但是使用伪元素margin-bottom却达到了效果:
#page:after,#page:before{
content: "";
display: table;
}
#page:after{
clear:both;
overflow: hidden;
}
只不过左右浮动的两个面板还是会换行显示。
具体原因是因为盒模型导致的。
加上如下样式:换行的显示问题得到了解决。
#header,
.main,
.sidebar,
#footer {
-webkit-box-sizing:border-box;
-moz-box-sizing:border-box;
-o-box-sizing:border-box;
-ms-box-sizing:border-box;
box-sizing:border-box;
}
其中默认的box-sizing值为content-box
页面效果如下: