CSS盒模型
盒子组成
- content
- padding
- border
- margin
盒模型注意点
- padding不能为负值,而margin可以
- 背景色会平铺到非margin的区域(背景色会平铺到content、padding、border部分)
- margin-top传递的现象及解决方案
.box1 {
width: 200px;
height: 200px;
background: pink;
}
.box2 {
width: 100px;
height: 100px;
background: blue;
margin-top: 20px; 这里的margin-top会连带父级一起margin-top20px
}
<div class="box1">
<div class="box2"></div>
</box>
解决方案: 1、使用padding-top 2、或者给父元素添加border
- margin上下叠加的现象及解决方案
.box1 {
width: 200px;
height: 200px;
background: pink;
margin-bottom: 30px; 取最高值,所以两个margin叠加,是30px
}
.box2 {
width: 100px;
height: 100px;
background: blue;
margin-top: 20px;
}
<div class="box1"></box>
<div class="box2"></div>
marked: 在Flexbox或网格布局中,不存在margin-top、bottom叠加及margin-top传递现象
块级盒子和内联盒子
- 块级盒子
独占一行
支持所有样式
不写宽度时,跟父容器相同
所占区域是一个矩形
- 内联盒子
盒子不会产生换行
有些样式不支持,例如width,height、上下margin
不写宽度时,宽度由内容决定
所占区域不一定是矩形
内联标签之间会有空隙
标准盒模型和怪异盒模型(IE盒模型)
- 标准盒模型
在标准模型中,如果给盒子设置width和height,实际设置的是content box。padding和border再加上设置的宽高一
起决定了整个盒子大小
- 怪异盒模型
内容宽度是该宽度减去边框和填充部分
当没有padding和border时,content决定整个盒子的width和height
一旦加入padding或border,整个盒子width和height不会发生改变,而是会把content往里缩
整理:
content-box:width、height => content
border-box:width、height => content + padding + border