p.inside是父元素,h2是其子元素,h2设置了margin-top:20px;
第一张图片的蓝色区域,就是父元素的高度,但是从第二张图片可以看出,父元素
的高度没有包裹子元素的margin-top,这是为什么啊?
PHP中文网2017-04-17 15:06:35
The reason why this problem occurs is that according to the specification : if a box does not have a padding (padding-top
) and a top border (border-top
), then the box
child will overlap the top margin of the first child element in its inner document flow.
The white point is : the top margin of the first child element of the parent element margin-top
if it cannot encounter a valid border或者padding
.
You will continue to find trouble with your "leader" (parent element, ancestor element) layer by layer. Just set a valid border或者padding
for the leader
Effectively control this leaderless margin
to prevent it from jumping over the hierarchy, falsely spreading the imperial edict, and executing its own margin as the leader's margin
. For vertical margins
The solution to merging has been explained above. Adding a border-top或者padding-top
to the middle element in the parent element example can solve this
question.
For detailed content, please refer to the blog post: http://www.cnblogs.com/az96/p...
ringa_lee2017-04-17 15:06:35
What is the css of the parent element?
The guess is that there is a margin merging problem, see here
PHP中文网2017-04-17 15:06:35
If there are no top border, top padding, inline content, and clear float attributes in the block-level parent element (for top border and top padding, it can also be said that when the top border and top padding When the width is 0), then the top margin of this block-level element and its first child element can be said to be "close to each other". At this time, the upper margins of the block-level parent element and its first child element will merge. In other words, the margins displayed by the parent element at this time will directly become the parent element and its first child element. The larger of the margin-top of the child element.
Similarly, if there is no separation between the margin-bottom of the block-level parent element and the margin-bottom of its last child element by the border, padding, inline content, height, min-height, and max-height of the parent element , the phenomenon of lower margin merging will occur.
For details, please refer to margin-collapse
To solve this problem, the simplest way is to add border/padding value to the parent element .
As shown in the figure:
The parent element does not add a border——
Parent element plus border——