盒模型的基本概念
盒模型是描述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: 200, y: 310, width: 946, height: 300, top: 310, …}
bottom:610
height:300
left:200
right:1146
top:310
width:946
x:200
y:310
__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: 100%;
height: 300px;
}
p{
margin-top: 10px;
margin-bottom: 20px;
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: 100%;
height: 300px;
}
.layout .left{
float: left;
width: 200px;
height: 200px;
background-color: rebeccapurple;
}
.layout .right{
height: 100%;
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: 30px;
background-color: rebeccapurple;
}
</style>
<div class="floatItem">
我是浮动元素
</div>
</section>