The child element margin-top makes the parent element move down

This is a memorable problem. The first time I encountered it was in the technical department of the school. At that time, I shared this problem with other members. Later, I wrote less on the front end. After 2 years, I practiced in the WeChat applet. Encountered this problem for the first time.

 

Here is an easy-to-understand explanation from other people's blogs:

When an element is contained within another element, their top and/or bottom margins also merge, assuming there is no padding or border separating the margins . Please see the picture below

Besides, the white point is: if the margin-top of the first child element of the parent element does not meet a valid border or padding, it will continue to find its own "leadership" layer by layer (parent element, ancestor element) Trouble. As long as you set an effective border or padding for the leader, you can effectively control this leaderless margin to prevent it from leapfrogging, falsely preaching imperial edicts, and implementing your own margin as the leader's margin.
The solution to vertical margin merging has been explained above, adding a border-top or padding-top to the parent element can solve this problem. (Quoting https://www.hicss.net/do-not-tell-me-you-understand-margin/ this article)

Solution:

1. Modify the height of the parent element and add padding-top style simulation (commonly used);
2. Add overflow:hidden; style to the parent element (perfect);
5. Declare floating for the parent element or child element (available);
3 .Add a border to the parent element (available);
4. Add an additional element to the front of the child element, set the height to 1px, overflow:hidden (if it is an inline element, it needs to be declared as a block element) (long-winded); 6.
For Parent or child elements declare absolute positioning (...).

 

 

Guess you like

Origin blog.csdn.net/qq_34507736/article/details/84334103
Recommended