MDN describes the following about the img element in “styling with CSS” section.
<img> has no baseline, so when images are used in an inline formatting context with vertical-align: baseline, the bottom of the image will be placed on the text baseline.
That said, I recently had a problem with an image related to a small gap under it. This is my code:
p {
border: 5px red solid;
margin: 0;
}
<img src="https://images.unsplash.com/photo-1661177405620-24e65f27ac0e?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1470&q=80" width="250px" />
<p>This is a paragraph with a gap above it</p>
My question is: Why does my image have this gap?, even if I am using it in a block formatting context triggered by the <p> element which is a block-level element.
How is the inline formatting context triggered in this case?
My image should only have that gap if I am using it in an inline fomatting context but this is not the case.
I may have the misconception on the subject. Any clarification is much appreciated. Thanks!
CodePudding user response:
The img
will be inside an anonymous block element and inside that anonymous block you have an inline formatting content. You can read more about it here: https://www.w3.org/TR/CSS2/visuren.html#anonymous-block-level
the DIV appears to have both inline content and block content. To make it easier to define the formatting, we assume that there is an anonymous block box around "Some text".
It's like you have the following where the div
is the anonymous block box that create a inline formatting context inside it
p {
border: 5px red solid;
margin: 0;
}
div {
outline: 1px solid green
}
<div><img src="https://images.unsplash.com/photo-1661177405620-24e65f27ac0e?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1470&q=80" width="250px" /></div>
<p>This is a paragraph with a gap above it</p>