Small problems are always easy to let people ignore, and in the interview when a face, because the simple question caused an embarrassing situation, then accumulate over a long period of time, often remember, familiar in the heart!

Margin collapse

In the parent element, set margin to 100px for the parent element and 50px for the child element

Amazing discovery, the result is beyond our expectations! The horizontal distance is fine, but in the vertical direction, when the child element is set to 50px from the top, it should be 50px from the top of the parent element.

This phenomenon is called margin collapse. But a lot of people may not understand, why is it called collapse? In the example above, the parent element was 50px from the top of the parent element, and now it is no longer there. This means that the parent element’s ceiling has no effect on the child element. That’s why it’s called margin collapse.

A sentence summary: the parent-child nested element vertical direction of the maximum margin.

But sometimes we don’t want to have such a problem, then how can we solve the problem of margin collapse?

The answer is, we can solve it by triggering the BFC! What is BFC?

BFC What is BFC and action

Block Formatting Context: Block level Formatting Context.

CSS treats each element of HTML as a box, and it further considers that each box contains a set of normal syntax rules, or rendering rules, according to which it can draw written HTML elements, but we can trigger the BFC by certain means. Make it conform to a slightly different syntax rule than the original syntax rule.

That is, when the BFC is triggered, a particular box will follow a different set of syntax rules.

BFC sounds like an amazing way to change the syntax of a box, but it doesn’t really change much. Probably less than one in a thousand. But this little bit of it will solve the problem of margin collapse and margin merger

How do I trigger the BFC

Summary of triggering BFC method: Float property is left/right overflow is hidden/scroll/auto position is absolute/fixed display is inline-block/table-cell/table-caption There are so many ways to trigger BFC, which one is better? Depending on the specific situation, I think a principle: according to the requirements, to see which trigger method has no effect on that