Daily learning - Why does margin overlap and how to solve it

Most people know that adjacent margins of block-level elements overlap. Most of them know the solution, but why is there overlap? ?

  • I found a good explanation on stackoverflow: The definition of margin is not to make the element move xxpx, but there must be a blank of xxxpx next to this element.

  • After getting this explanation, think about the problem of "adding a 20px top margin to the first child element, the parent element actually sinks with the child element", and then think about the solution. Add overflow to the parent element to open a BFC, or add padding, border, etc. to the parent element. This approach makes the side border of the element not the previous box but the parent element. The relative position of the blank that must exist has changed. At this time , The child element will no longer "influence" the position of the parent element.

  • Generally, the problem can be solved by setting overflow: hidden; to the parent element. The reason for this situation is that as long as the vertical outer margins are directly contacted between the ordinary document flow boxes, the merge will occur. After the merge, the visual height of the outer margins is taken to be two. The larger of the merged margins. This phenomenon occurs in three situations: the merge of adjacent sibling block elements, the parent element and its first child element and the last child element (without margins or borders separating the outer margins), and the merging of empty block-level elements themselves.

  • Solution:
    When two boxes in the same BFC overlap in the vertical direction, you can wrap a container outside one of the boxes and use it to trigger a BFC, so that the two are in different BFCs. Will affect each other.

  • Conditions for starting BFC:
    1. Floating element, float value other than none
    2. Position value is not static or relative
    3. Display is not none
    4. Overflow value other than visible

Guess you like

Origin blog.csdn.net/Beth__hui/article/details/113389152