Instead of following the common advice to use a background-image, I recommend utilizing an actual image element and scaling it with object-fit: cover
. There are two key reasons for this approach:
- You reap the SEO and accessibility benefits of incorporating a genuine image element
- You gain access to all the advantages that come with using image elements, such as leveraging srcset to deliver different sizes to various devices and implementing lazy loading.
Here is the method you can follow:
Html
<div class="container">
<img
src="imageurl.jpg"
srcset="*optional*"
sizes="*optional*"
alt="My image"
/>
</div>
Css
.container {
position: relative;
width: 80vw; /* Or adjust to desired size */
height: 50vh; /* Or adjust to desired size */
}
.container img {
position: absolute;
top: 0;
width: 100%;
height: 100%;
object-fit: cover;
}
If the container does not have fixed width/height, you can utilize an aspect ratio like so:
.container {
position: relative;
width: 100%;
height: 0;
padding-bottom: 56.25%; /* 16:9 aspect ratio */
}