本文是面试汇总分支——说一下CSS盒模型。css
一. 基本概念html
盒模型的组成,由里向外content,padding,border,margin。前端
盒模型有两种标准,一个是标准模型,一个是IE模型。面试
标准模型以下图浏览器
因此盒子总宽度为:width+border+padding dom
IE盒模型以下图布局
因此盒子总宽度为:width post
二. CSS如何设置这两种模型flex
这里用到了CSS的属性box-sizingurl
/* 标准模型 */ box-sizing:content-box; /*IE模型*/ box-sizing:border-box;
三. JS如何获取盒模型对应的宽和高
为了方便书写,如下用dom来表示获取的HTML的节点。
1. dom.style.width/height
这种方式只能取到dom元素内联样式所设置的宽高,也就是说若是该节点的样式是在style标签中或外联的CSS文件中设置的话,经过这种方法是获取不到dom的宽高的。
2. dom.currentStyle.width/height
这种方式获取的是在页面渲染完成后的结果,就是说无论是哪一种方式设置的样式,都能获取到。
但这种方式只有IE浏览器支持。
3. window.getComputedStyle(dom).width/height
这种方式的原理和2是同样的,这个能够兼容更多的浏览器,通用性好一些。
4. dom.getBoundingClientRect().width/height
这种方式是根据元素在视窗中的绝对位置来获取宽高的。
5.dom.offsetWidth/offsetHeight
这个就没什么好说的了,最经常使用的,也是兼容最好的。
四. 根据盒模型解释边距重叠
什么是边距重叠
以下图,父元素没有设置margin-top,而子元素设置了margin-top:20px;能够看出,父元素也一块儿有了边距。
上图的代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> *{ margin:0; padding:0; } .demo{ height:100px; background: #eee; } .parent{ height:200px; background: #88f; } .child{ height:100px; margin-top:20px; background: #0ff; width:200px; } </style> </head> <body> <section class="demo"> <h2>此部分是能更容易看出让下面的块的margin-top。</h2> </section> <section class = "parent"> <article class="child"> <h2>子元素</h2> margin-top:20px; </article> <h2>父元素</h2> 没有设置margin-top </section> </body> </html>
五. BFC(边距重叠解决方案)
首先要明确BFC是什么意思,其全英文拼写为 Block Formatting Context 直译为“块级格式化上下文”。
代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> *{ margin:0; padding:0; } .top{ background: #0ff; height:100px; margin-bottom:30px; } .bottom{ height:100px; margin-top:50px; background: #ddd; } </style> </head> <body> <section class="top"> <h1>上</h1> margin-bottom:30px; </section> <section class="bottom"> <h1>下</h1> margin-top:50px; </section> </body> </html>
效果图
用bfc能够解决垂直margin重叠的问题
关键代码
<section class="top"> <h1>上</h1> margin-bottom:30px; </section> <!-- 给下面这个块添加一个父元素,在父元素上建立bfc --> <div style="overflow:hidden"> <section class="bottom"> <h1>下</h1> margin-top:50px; </section> </div>
效果图
关于bfc的应用的案例这里就不在一一举出了,你们去网上找一些其余的文章看一下。
感谢: