CSS3-盒子模型
lijiacheng 2024-03-20 css3
# 什么是盒子模型
盒子模型就是元素在网页中实际占据的大小
# 盒子模型的计算方式
盒子模型 = width/height+padding+border 注意:没有margin
# box-sizing
当box-sizing的值为 border-box 时,会改变盒子模型的计算方式
盒子模型 = width/height = 内容宽高+border+padding
# offsetWidth
JavaScript中获取盒子模型的方式是 obj.offsetWidth / offsetHeight
# margin负值有什么效果?
- margin-left 负值,元素自身向左移动
- margin-top 负值,元素自身向上移动
- margin-right 负值,右边的元素向左移动
- margin-bottom 负值,下边的元素向上移动
# 什么是BFC
BFC 是 Block Formatting Context (块级格式上下文)的缩写
BFC是一个独立的空间,里面子元素的渲染不影响外面的布局
# BFC作用
1、解决margin塌陷
2、清除浮动
# 如何触发BFC
- overflow: hidden
- display: inline-block / table-cell / flex
- position: absolute / fixed
解决margin塌陷
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>bfc</title>
</head>
<style>
* {
margin: 0;
padding: 0;
}
section {
width: 200px;
height: 200px;
background: #ccc;
margin: 20px;
}
.box {
display: inline-block;
background: black;
}
.left {
float: left;
}
.right {
float: right;
}
</style>
<body>
<div class="box">
<section class="left">left</section>
<section class="right">right</section>
</div>
</body>
</html>
清除浮动
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>bfc</title>
</head>
<style>
* {
margin: 0;
padding: 0;
}
section {
width: 200px;
height: 200px;
background: #ccc;
margin: 50px;
}
.box {
overflow: hidden;
}
</style>
<body>
<div class="box">
<section>section1</section>
</div>
<section>section2</section>
</body>
</html>