Responsive, semantic images with CSS
CSS tip:
object-fityour images.
To have an image that doesn’t try to stretch to its width/height the classic CSS is as follows:
.thumbnail {
width: 50px;
height: 50px;
background-size: cover;
background-position: center;
}
With this associated HTML (inline styles… 👎):
<div
class="thumbnail"
style="background-image: url('some-url');"
>
</div>
We can do:
.thumbnail {
width: 50px;
height: 50px;
object-fit: cover;
object-position: center;
}
With the following HTML:
<img class="thumbnail" src="some-url">
This was sent out on the Code with Hugo newsletter last Monday. Subscribe to get the latest posts right in your inbox (before anyone else).
Why is this cool?
- One word: accessibility.
- Two words: semantic markup.
- Many words, with the
div+background-imagesolution:- if the URL turned out to be broken, it would show empty space, with the
img+object-fitone, it shows the good old “broken image because of URL” fallback (oraltattribute value). - An
imgtag is more accessible since we can havealt - Typing
src="my-url"is just less characters thanstyle="background-image: url('my-url')".
- if the URL turned out to be broken, it would show empty space, with the
Warning: this might not work on older browsers, it does, however gracefully degrade (the image will just be stretched), it won’t mess up the layout though.
Interested in Alpine.js?
Power up your debugging with the Alpine.js Devtools Extension for Chrome and Firefox. Trusted by over 15,000 developers (rated 4.5 ⭐️).
orJoin 1000s of developers learning about Enterprise-grade Node.js & JavaScript