<!DOCTYPE html>
<html lang="en">
<head>
<title>test</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
.a{
height:48px;
background: #eee;
}
.b{
height:520px;
background: #ff4949;
}
.c{
width:90%;
height:300px;
margin:20px auto;
background: #fff;
}
</style>
</head>
<body>
<p class="a"></p>
<p class="b">
<p class="c"></p>
</p>
</body>
</html>
p.c 不是应该被红色环绕吗?烦请那个老哥解释下。
Because in BFC, two adjacent (brothers or father-son), no borders and no padding, the margin-top of an element and the margin-top of its first regular document flow child element will produce margin-collapse (outer margin from folding).
You add a border to b,
Or add padding,
can be eliminated.
Alternatively, you can add
overflow: hidden;
to b.You can refer to: In-depth understanding of BFC and Margin Collapse
Just add overflow: hidden; in .b.
Because overflow uses values other than visible (hidden, auto, scroll) will trigger BFC.
What is BFC?
Block Formatting Contexts (block-level formatting context)
Elements with BFC can be regarded as isolated independent containers. The elements inside the container will not affect the layout of the outside elements, and BFC has ordinary containers. There are some features that it does not have, such as the ability to contain floating elements. The second type of float clearing method mentioned above (such as the overflow method) triggers the BFC of the parent element of the floating element, so that it can contain floating elements, thereby preventing height collapse. problem.
overflow: hidden; You add this sentence to p.b.
Search for “child element margin affects parent element”
This is called overlapping margins. The margins of the child elements will affect the parent elements, and the larger the margins of the two, the larger the margins of the entire container. At this time, you should choose to trigger BFC. The previous ones have made it very clear what BFC is. The situations that trigger BFC are:
Root element
float attribute is not none;
position is absolute or fixed;
display is inline-block, table-cell, table-caption, flex, inline-flex;
overflow is not visible;
Solution: