21 NOVEMBER 2019
Prerequisite: The aspect ratio of the placeholder space is known. E.g. an image with ratio 16:9.
There are two key steps:
padding-top
of 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.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 below 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. Best to ensure you have the correct image crops to handle all screen sizes you intend to support.
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%
}