CSS盒模型

323 阅读2分钟

本文已参与掘金创作者训练营第三期「高产更文」赛道,详情查看:掘力计划|创作者训练营第三期正在进行,「写」出个人影响力

1. 类别

  1. IE盒模型-border-box
  2. W3C标准盒模型-content-box

2. 特点(注:图片来源网络,侵删)

2.1 W3C标准盒模型
   width=content;
   height=content;

标准模型

2.2 IE盒模型
width=content+padding+border
height=content+padding+border

在这里插入图片描述

3. CSS如何设置这两种模型

标准模型:box-sizing:content-box IE模型:box-sizing:border-box

4. JS如何设置/获取盒模型对应的宽高

  1. dom.style.width/height:内联样式的宽高,返回值带单位,返回值的数据类型是string--300px

  2. dom.currentStyle.width/height:渲染后的最终宽高(旧版IE中使用),它获取的数据类型是字符串,如300px

  3. window.getComputedStyle(dom).width/height:DOM标准,不支持IE

  4. dom.getBoundingClientRect().width/height:它获取的数据类型是字符串,如300px

5.兼容写法:

var oAbc = document.getElementById("abc");
if(oAbc.currentStyle) {
	alert("我支持currentStyle");
	alert(oAbc.currentStyle.width);
} else {
	alert("我不支持currentStyle");
	alert(getComputedStyle(oAbc,false).width);
}
5. 边距重叠
5.1 边界重叠是指两个或多个盒子(可能相邻也可能嵌套)的相邻边界(其间没有任何非空内容、补白、边框)重合在一起而形成一个单一边界。

例1:

       .neighbor{
			height: 100px;
			background: red;
		}
		.father{
			background: #f436365e;
		}
		.child{
			height: 100px;
			margin-top: 10px;
			background: #00800047;
		}
		<div class="neighbor">
		this is neighbor
	</div>
	<div class="father">
		<div class="child">
			this is child
		</div>
	</div>

实际效果: 实际效果 但是我们期望的效果是下面这个: 预期效果 解决方案:使用BFC

.father{
			background: #f436365e;
			overflow: hidden;
		}
5.2 两个或多个块级盒子的垂直相邻边界会重合,它们的边界宽度是相邻边界宽度中的最大值。注意水平边界是不会重合的。

例2:

<style type="text/css">
		
		.father{
			background: #f436365e;
			overflow: hidden;
		}
		.child{
			height: 20px;
			margin: 30px auto 30px;
			background: #00800047;
		}
	</style>
	<div class="father">
		<div class="child">
			this is child1
		</div>
		<div class="child">
			this is child2
		</div>
		<div class="child">
			this is child1
		</div>
	</div>

实际效果:间隔只有30px 实际效果

预期的效果: 预期有60px 在这里插入图片描述

解决方案:使用BFC

<div class="father">
		<div class="child">
			this is child1
		</div>
		<div style="overflow: hidden;">/*在第二个div加了新的一层div*/
			<div class="child" >
				this is child2
			</div>
		</div>
	
		
		<div class="child">
			this is child1
		</div>
	</div>