布局中的BFC作用和Flex容器
BFC的三个作用
1.解决外边距合并
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="x.css" />
<title>Document</title>
</head>
<body>
<div class="container">
<div class="box"></div>
<div class="box"></div>
</div>
</body>
</html>
.container {
.box {
width: 10em;
height: 10em;
margin: 1em;
background-color: blue;
border-radius: 1em;
}
}
- 外边距相邻两元素触发BFC可以在外部分别用BFC元素包裹,触发后的元素形成独立的空间,不被外部影响。 如下
<div class="container">
<div class="out-box">
<div class="box"></div>
</div>
<div class="out-box">
<div class="box"></div>
</div>
</div>
.container {
.out-box {
overflow: hidden;
.box {
width: 10em;
height: 10em;
margin: 1em;
background-color: blue;
border-radius: 1em;
}
}
}
2.清除浮动
<div class="container">
<div class="box"></div>
</div>
.container {
border: 1px solid red;
.box {
float: left;
width: 10em;
height: 10em;
background-color: blue;
border-radius: 1em;
}
}
- 子元素浮动,脱离文档标准流,通过父容器触发BFC清除浮动,计算子元素的高度 如下
.container {
border: 1px solid red;
overflow: hidden;
.box {
float: left;
width: 10em;
height: 10em;
background-color: blue;
border-radius: 1em;
}
}
3.阻止元素被浮动元素覆盖
<div class="container">
<div class="box"></div>
<div class="box"></div>
</div>
.container {
.box:nth-child(1) {
float: left;
width: 5em;
height: 5em;
background-color: red;
}
.box:nth-child(2) {
width: 10em;
height: 10em;
background-color: blue;
}
}
- 兄弟元素浮动,脱离文档标准流,通过兄弟元素触发BFC达到阻止元素被浮动元素覆盖的目的
.container {
.box:nth-child(1) {
float: left;
width: 5em;
height: 5em;
background-color: red;
}
.box:nth-child(2) {
overflow: hidden;
width: 10em;
height: 10em;
background-color: blue;
}
}
flex容器常用的四个属性
justify-content: center;<br/>
align-items: center;<br/>
align-content: center;<br/>
flex-flow: row;
<div class="container">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
.container {
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
flex-flow: row wrap;
align-content: space-between;
.box {
width: 10em;
height: 10em;
background-color: blue;
margin: 1em;
}
}