盒模型的基本概念
盒模型是描述DOM元素位置的一種模型,它由内容(content)、内邊距(padding)、邊框(border)、外邊距(margin)組成, CSS盒子模式都具備這些屬性。
标準模型與IE盒模型的差別
1、寬高計算方式的差别
标準盒模型的寬度、高度隻包括内容的寬度高度。

IE盒模型的寬度、高度,包括content + height + border
2、當内容區(content)域超過width時的差別
當内容區超過width的範圍時:
标準盒模型的内容區會擴大,始終與width保持一緻。
怪異盒模型,會根據原有寬度(原來的width),優先保證border、padding,然後把剩下的區域分給content。并不會因為content變大,而width變大。
參考連結
通過CSS如何設定這兩種盒模型
/*标準盒模型*/
box-sizing: content-box;
/*怪異盒模型*/
box-sizing: border-box;
JS如何擷取或者設定盒模型對應的寬和高
let dom = document.getElementById("test")
方法一:
dom.style.width
結果為:
""
方法二:
dom.getBoundingClientRect(dom)
DOMRect {x: , y: , width: , height: , top: , …}
bottom:
height:
left:
right:
top:
width:
x:
y:
__proto__:DOMRect
方法三:
window.getComputedStyle(dom).width
window.getComputedStyle(dom).height
方法四:
currentStyle:該屬性隻相容IE,不相容火狐和谷歌
但是currentStyle.width在IE浏覽器下拿到的值是auto,因為css中沒有聲明寬度。如果聲明了寬度,那麼currentStyle.width得到的值是一個确定的值。
BFC的解決方案
BFC(邊距重疊解決方法)
BFC的基本概念
塊級格式化上下文,内聯格式化上下文(IFC)
從樣式上看,具有 BFC的元素與普通的容器沒有什麼差別,
從功能上看,BFC相當于建構了一個密閉的盒子模型,
在BFC中的元素不受外部元素的影響;
BFC的原理(BFC的渲染規則)
1、BFC在這個元素,垂直方向會發生重疊
2、BFC的區域,不會與浮動元素的Box重疊
3、BFC在頁面上是一個獨立的容器,
4、計算BFC高度時,浮動元素也會參與計算
如何建立一個BFC
- float:left ,right (非none屬性)
- position:absolute,fixed (非static屬性)
- display:inline-block,table-cell,table-caption;(行内塊元素與表格元素)
- overflow:hidden,auto,scroll (非 visible屬性)
- display: flow-root
- column-span: all
BFC的使用場景
1.bfc垂直方向邊距重疊
<!--bfc垂直方向邊距重疊-->
<section class="margin">
<style>
.margin{
width: %;
height: px;
}
p{
margin-top: px;
margin-bottom: px;
background-color: rebeccapurple;
}
.overflow{
overflow: hidden;
}
</style>
<p>1</p>
<div class="overflow">
<p>2</p>
</div>
<p>3</p>
</section>
2、BFC不與float重疊
<!--BFC不與float重疊-->
<section class="layout">
<style>
.layout{
background-color: aqua;
width: %;
height: px;
}
.layout .left{
float: left;
width: px;
height: px;
background-color: rebeccapurple;
}
.layout .right{
height: %;
overflow: auto;
background-color: green;
}
</style>
<div class="left">
我是浮動
</div>
<div class="right" id="test">
我是右側
</div>
</section>
3、BFC子元素,即使是float,也會參與計算。一種清除浮動的方式
<!--BFC子元素,即使是float,也會參與計算。一種清除浮動的方式-->
<section class="float">
<style>
.float{
overflow: auto;
/*display: inline-block;*/
}
.floatItem{
float: left;
font-size: px;
background-color: rebeccapurple;
}
</style>
<div class="floatItem">
我是浮動元素
</div>
</section>