One solution is to set a fixed aspect ratio for the containing element (such as a div) and then use CSS to set the background-image of the element to the lazy-loaded image. This ensures that the container element maintains its aspect ratio, even as the actual image is loaded and its dimensions change.
For example, if you want a container element with a 16:9 aspect ratio, you can set the following CSS:
.container {
position: relative;
width: 100%;
padding-bottom: 56.25%; /* 16:9 aspect ratio */
background-position: center center;
background-size: cover;
}
.container > img {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
object-fit: cover;
}
Then, you can lazily load the image as follows:
<div class="container">
<img data-src="lazy-image.jpg" class="lazyload" />
</div>
The lazyload
class can be used with a third-party JavaScript library (such as lazysizes or Intersection Observer) to lazily load the image while the data-src
attribute holds the URL of the lazy-loaded image.
With this approach, once the image has loaded, it will be resized to fit the container while maintaining its aspect ratio without disrupting the content layout.
Asked: 2022-11-19 11:00:00 +0000
Seen: 8 times
Last updated: Jul 14 '21