Margin merges and margin collapses - the problem of using margin-top to apply the first element to the parent element

When using Uniapp to do projects, I encountered the problem of margin merging and margin collapse. I will record it here and share the solution.

Problem: When two containers are nested, if there are no other elements between the outer container and the inner container, the margin-top of the inner element will be applied to the parent element.

Using argin-top, the first element is abnormal , there is no gap, but it is applied to the parent element ( margin collapse is also called margin merging ), while the second and third elements are normal, as shown below.

In the situation shown above, there is a problem of margin merging and margin collapse.

Solution: It can be solved by triggering BFC (full name Block Formatting Context, block-level formatting context). The solution is as follows:

Method 1. Add border to parent

For example: border:1px solid #00FFFF;

Method 2. Add padding to the parent

For example: padding:1px;

Method 3: Use overflow to solve collapse.

For example: overflow: hidden;

Method 4. Add position:fixed to the parent element;

Use the knowledge of positioning to display the parent element at a fixed position so that it will not be affected by the problem of margin-top collapse.

Method 5. Set display: table to the parent element;

Method 6. Use pseudo elements

.clearfix::before{
    content: '';
    display: table;
}

Just add the clearfix class name to the element that needs to be cleared of collapse.

Reasons for collapse:

If the top margin-top of the first child element of the parent element cannot encounter a valid border or padding or non-empty content, the margin-top of the parent element will be merged layer by layer into a single margin-top. Therefore, as long as you set a valid border or padding on the parent element or add a non-empty content (such as text) before the child element, you can prevent it from merging the parent element's margins.

After modification, it was successfully solved, as shown below. It can now be seen that the first element interval also appears normally.

Guess you like

Origin blog.csdn.net/weixin_42100033/article/details/132570937