什么是盒模型?
在HTML页面中,每一个元素都可以看做事一个盒子;而这个盒模型由:内容区(content)、填充区(padding)、边框区(border)、外边界区(margin)四部分组成。
盒模型有哪两种?
标准模式下:一个块的总宽度(页面中占的宽度)=width+margin(左右)+padding(左右)+border(左右)
怪异模式下:一个块的总宽度=width+margin(左右)(width已经包含了padding和padding值)
标准和怪异模型的转换
box-sizing:content-box
;将采用标准模式下的盒子模型;
box-sizing:border-box
;将采用怪异模式下的盒子模型;
box-sizing:inherit
;规定应从父元素继承 box-sizing 属性的值。
JS盒模型
JS中怎么获取和设置box的内容宽高:
在IE中:dom.currentStyle.width/height
;
在非IE中:window.getComputedStyle(dom).width/height
var obj = document.getElementById("box");
var style = null;
if (window.getComputedStyle) {
style = window.getComputedStyle(obj, null); // 非IE
} else {
style = obj.currentStyle; // IE
}
alert("width=" + style.width + "\nheight=" + style.height);
盒模型产生的双边距重叠问题解决
可以使用BFC(块级格式化上下文
)解决
有两种双边距重叠的情况:
父子关系的边距重叠:
父子关系,如果子元素设置了外边距,在没有把父元素变成BFC的情况下,父元素也会产生外边距
给父元素添加overflow:hidden
这样父元素就会变为BFC,不会随子元素产生外边距
<style>
.out {
background-color: #f00;
width: 200px;
height: 200px;
}
.inner{
margin-top: 50px;
width: 100px;
height: 100px;
background-color: blue;
}
</style>
<div class="out">
<div class="inner"></article>
</div>
同级兄弟关系的重叠:
同级元素在垂直方向上外边距会出现重叠情况,最后外边距的大小取两者绝对值大的那个
可通过添加空元素或伪类元素,设置overflow:hidden;解决margin重叠问题
<style type="text/css">
.fat {
background-color: #ccc;
}
.fat .child-one {
width: 100px;
height: 100px;
margin-bottom: 50px;
background-color: #f00;
}
.fat .child-two {
width: 100px;
height: 100px;
margin-top: 20px;
background-color: #345890;
}
.fat .child-content{
overflow:hidden
}
</style>
<section class="fat">
<div class="child-top"></div>
<div class="child-content"></div>
<div class="child-bottom"></div>
</section>