Ensure to specify both height and width for your image in the inline CSS.
When you insert an <img/>
element, the browser cannot determine its dimensions until it communicates with the server.
Since you have embedded your CSS inline, the browser will render the page based solely on the initial request (your page HTML and inline styles).
Due to this, it attempts to calculate the layout, scans your inline CSS for size details of the image, fails to find any information regarding width, and therefore struggles to allocate horizontal space for the image.
The browser later fetches the image from your server, acquires the dimensions, and then allocates 400px
by 400px
for it.
This results in a layout shift from a space that was initially 0px
wide and 400px
tall to one that is now 400px
wide and 400px
tall (plus a 1px border).
You were close by setting a min-height
for the image, but it is also essential to define a min-width
.
Therefore, your CSS should be:
div[itemprop="image"] {
display: inline-block;
float: left;
margin-right: 10px;
min-height: 400px;
min-width: 400px;
}
An Alternative Approach for Handling Images
Instead of specifying fixed sizes for images, consider using a responsive design.
In this method, you add the image within a <div>
, which has a percentage-based width defined.
Subsequently, place your <img/>
inside that <div>
with width: 100%
.
This resolves the issue of the browser needing to compute the width.
To address the height, add width="400"
and height="400"
to your <img/>
.
Most browsers utilize this information to calculate the image's aspect ratio
.
By doing so, the browser can allocate sufficient vertical space by multiplying the width by the aspect ratio.
Illustration
In the following example, note that I set the <img/>
width to 40 and height to 40.
This demonstrates that the specific values do not matter as long as they maintain the correct aspect ratio. For instance, on a 16:9 image, you could set width="16"
and height="9"
, even for an image sized 800 by 450 pixels.
The browser follows this process:
- Determine the div's size on screen (on a 660px wide screen, it is 200 pixels).
- Evaluate the image's width (100% * 200 pixels = 200 pixels).
- Calculate the aspect ratio (width / height => 40 / 40 = 1:1).
- Multiply the derived width by the height (200 pixels * 1).
Hence, the browser assigns a 200px by 200px area for the image before initiating the request, eliminating any layout shifts.
<style>
.holder{
width: 33%;
background-color: #333;
}
img{
width: 100%;
height: auto;
}
</style>
<div class="holder">
<img src="https://placehold.it/400x400" width="40" height="40" />
</div>
<p>text that will not move</p>