本文主题:css
什么是 CSS 盒模型?相信大部分人都能答出这个问题来,那就是 标准模型 + IE 模型html
标准模型:面试
IE 模型segmentfault
很明显浏览器
width
和 height
指的是内容区域的宽度和高度。增长内边距、边框和外边距不会影响内容区域的尺寸,可是会增长元素框的总尺寸。width
和 height
指的是content
+border
+padding
box-sizing: content-box;
box-sizing: border-box;
dom.style.width/height
: 只能取出内联样式的宽和高 eg: <div id="aa" style="width: 200px"></div>
dom.currentStyle.width/height
获取即时计算的样式,可是只有 IE 支持,要想支持其余浏览器,能够经过下面的方式window.getComputedStyle(dom).width
: 兼容性更好dom.getBoundingClientRect().width/height
: 这个较少用,主要是要来计算在页面中的绝对位置什么是边距重叠呢?dom
边界重叠是指两个或多个盒子(可能相邻也可能嵌套)的相邻边界(其间没有任何非空内容、补白、边框)重合在一块儿而造成一个单一边界。布局
<style> .parent { background: #e7a1c5; } .parent .child { background: #c8cdf5; height: 100px; margin-top: 10px; } </style>
<section class="parent">
<article class="child"></article>
</section>
复制代码
觉得期待的效果:spa
而实际上效果以下:3d
在这里父元素的高度不是 110px,而是 100px,在这里发生了高度坍塌。code
缘由是若是块元素的 margin-top
与它的第一个子元素的 margin-top
之间没有 border
、padding
、inline
content
、 clearance
来分隔,或者块元素的 margin-bottom 与它的最后一个子元素的 margin-bottom 之间没有 border
、padding
、inline
content
、height
、min-height
、 max-height
分隔,那么外边距会塌陷。子元素多余的外边距会被父元素的外边距截断。
<style> #margin { background: #e7a1c5; overflow: hidden; width: 300px; } #margin > p { background: #c8cdf5; margin: 20px auto 30px; } </style>
<section id="margin">
<p>1</p>
<p>2</p>
<p>3</p>
</section>
复制代码
能够看到 1 和 2,2 和 3 之间的间距不是 50px,发生了边距重叠是取了它们之间的最大值 30px。
假设有一个空元素,它有外边距,可是没有边框或填充。在这种状况下,上外边距与下外边距就碰到了一块儿,它们会发生合并:
解决上述问题的其中一个办法就是建立 BFC。BFC 的全称为 Block Formatting Context
,即块级格式化上下文。
父子元素的边界重叠得解决方案: 在父元素上加上 overflow:hidden;使其成为 BFC。
.parent {
background: #e7a1c5;
overflow: hidden;
}
复制代码
兄弟元素的边界重叠,在第二个子元素建立一个 BFC 上下文:
<section id="margin">
<p>1</p>
<div style="overflow:hidden;">
<p>2</p>
</div>
<p>3</p>
</section>
复制代码
<style> #float { background: #fec68b; } #float .float { float: left; } </style>
<section id="float">
<div class="float">我是浮动元素</div>
</section>
复制代码
父元素#float
的高度为 0,解决方案为为父元素#float
建立 BFC,这样浮动子元素的高度也会参与到父元素的高度计算:
#float {
background: #fec68b;
overflow: hidden; /*这里也能够用float:left*/
}
复制代码
<section id="layout">
<style> #layout { background: red; } #layout .left { float: left; width: 100px; height: 100px; background: pink; } #layout .right { height: 110px; background: #ccc; } </style>
<!--左边宽度固定,右边自适应-->
<div class="left">左</div>
<div class="right">右</div>
</section>
复制代码
在这里设置右边的高度高于左边,能够看到左边超出的部分跑到右边去了,这是因为因为浮动框不在文档的普通流中,因此文档的普通流中的块框表现得就像浮动框不存在同样致使的。
解决方案为给右侧元素建立一个 BFC,原理是 BFC 不会与 float 元素发生重叠。
#layout .right {
height: 110px;
background: #ccc;
overflow: auto;
}
复制代码
参考 边距重叠与 BFC