Responsive, semantic images with CSS
CSS tip: '
object-fit' your images.
To have an image that doesn’t try to stretch to its width/height the classic CSS is as follows:
With this associated HTML (inline styles… 👎):
We can do:
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
- if the URL turned out to be broken, it would show empty space, with the
object-fitone, it shows the good old “broken image because of URL” fallback (or
imgtag is more accessible since we can have
src="my-url"is just less characters than
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.
Get the latest posts delivered right to your inbox
Originally published at codewithhugo.com on July 5, 2018.