本文是面試彙總分支——說一下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的應用的案例這裏就不在一一舉出了,你們去網上找一些其餘的文章看一下。
感謝: