21 NOVEMBER 2019
Prerequisite: You know the aspect ratio for the image e.g. 16:9.
Steps:
padding-top
to a percentage of the width that gives the aspect ratio you want. E.g. padding top of 62.5% gives a 8:5 ratio. This works because padding top/bottom on an element is based on the current width. This means regardless of the current size of the image (large/small device) the ratio will be correct.position: absolute
so it fills the exact space left for it. The effect of this is that when the image loads it will sit in the exact space left for it, and not move the positioning of other elements around it.HTML
<div class="block-placeholder block-ratio-5by8">
<img src="~/images/abc.jpg" class="figure-img" alt="An image">
</div>
CSS
.block-placeholder {
position: relative
overflow: hidden
display: block
}
.block-ratio-5by8 {
padding-top: 62.5%
}
.figure-img {
left: 0
right: 0
top: 0
bottom: 0
position: absolute
height: 100%
width: 100%
}
As a final step you can set {image} max-width: 100%
to ensure it never overflows the space left for it. Alternatively you can use width: 100%
as I have above to ensure it is always stretches to fill the space - with the caveat that this may lead to the image being blurry if it is stretched too much.
Ensure you have a comprehensive set of image crops (with the same ratio) to handle all screen sizes you intend to support.
Example
Before image loads, placeholder space:
╭──────────────────╮
│▲ │
│| │
│62.5% │
│| │
│▼◄------100%-----►│
╰──────────────────╯
When image loads it fills space:
╭──────────────────╮
│ //\\ │
│ // \\ │
│ //\\// \\ │
│ // // \\ │
│ //. _. _. _. _\\ │
╰──────────────────╯