As shown in the figure below, when I select the first a tag, the browser will include the following a tag, and the margin of the P element in the A tag is also collapsed with the .box2.How to explain this ?
.box1 {
width: 100px;
height: 100px;
background-color: antiquewhite;
}
p {
margin-top: 10px;
}
<div ></div>
<div >
<a href="#">
<p>abc</p>
</a>
<a href="#">abc</a>
</div>
CodePudding user response:
You have a block element (the p
) inside an inline element (the link) then an inline element right after (the second link).
Here is a better illustration with some padding and outline.
p {
margin-top: 10px;
}
a:first-child {
padding: 0 5px;
outline: 1px solid red;
}
<div >
<a href="#">
<p>abc</p>
</a>
<a href="#">abc</a>
</div>
The use of a block element inside an inline one will activate a complex mechanism where you will have an inline content before the block element and another one after the block element (highlighted by the outline). And since you have another a
which is also an inline element, it will be on the same line with the second inline content.
The Devtool will show you the rectangular region that contain both inline contents (in red) and the block content (the p
) and also the next a
because it happen to be at the same line.
When an inline box contains an in-flow block-level box, the inline box (and its inline ancestors within the same line box) are broken around the block-level box (and any block-level siblings that are consecutive or separated only by collapsible whitespace and/or out-of-flow elements), splitting the inline box into two boxes (even if either side is empty), one on each side of the block-level box(es). The line boxes before the break and after the break are enclosed in anonymous block boxes, and the block-level box becomes a sibling of those anonymous boxes. When such an inline box is affected by relative positioning, any resulting translation also affects the block-level box contained in the inline box. ref