Article tags
- css,
- images
Semantic Image Overlays With Object-Fit
Think of how many times you have coded a grid of images with an overlay that appears on hover and displays some sort of text. With the object-fit
property getting wider support, there is now a clean, semantic way to do this.
Without object-fit
Here’s how I used to accomplish this:
<article class="blog-post-teaser">
<div
class="image"
style="background-image: url(...)"
></div>
<div class="overlay">
<h2>
<a href="...">
Article Title
</a>
</h2>
</div>
</article>
The markup involved an article
containing a div
with a background image applied, and an overlay div
that contained the text that needed to sit on top of the image. I would then absolutely position both the image and the overlay. The size of the div
would be determined by a percentage padding trick on the article:
.blog-post-teaser {
position: relative;
padding: 30% 0;
}
.blog-post-teaser .image {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.blog-post-teaser .overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
The key downside with this approach is that it’s not as semantic as it could be. The image for each article seems like a pretty important piece of content, and the browser doesn’t know that it’s an image. And we can’t feed in alt
tags to help with SEO.
How do we improve semantics while retaining control of the image sizing? Enter object-fit
.
With object-fit
Here’s what my markup looks like now:
<article class="blog-post-teaser">
<figure>
<img src="..." alt="...">
<figcaption>
<h2>
<a href="...">
Article Title
</a>
</h2>
</figcaption>
</figure>
</article>
Now the browser knows we’re serving up an image. It even knows that the article title is both a heading for the article and a caption for the image. Search engines can now access alt text. Let’s look at the styling:
.blog-post-teaser figure {
position: relative;
padding: 30% 0;
}
.blog-post-teaser figcaption {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.blog-post-teaser img {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
object-fit: cover;
}
It’s almost identical, only that now we’re using the img
element and applying the object-fit
property. This works the exact same way as setting background-size: cover
. The image will fill the specified space.
Now the browser knows we’re serving up an image. Search engines can properly access alternative text.