DEV Community

Cover image for Responsive, semantic images with CSS
Hugo Di Francesco
Hugo Di Francesco

Posted on • Originally published at codewithhugo.com on

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:

.thumbnail {
  width: 50px;
  height: 50px;
  background-size: cover;
  background-position: center;
}
Enter fullscreen mode Exit fullscreen mode

With this associated HTML (inline styles… 👎):

<div
  class="thumbnail"
  style="background-image: url('some-url');"
>
</div>
Enter fullscreen mode Exit fullscreen mode

We can do:

.thumbnail {
  width: 50px;
  height: 50px;
  object-fit: cover;
  object-position: center;
}
Enter fullscreen mode Exit fullscreen mode

With the following HTML:

<img
  class="thumbnail"
  alt="My thumbnail"
  src="some-url">
Enter fullscreen mode Exit fullscreen mode

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?

  1. One word: accessibility.
  2. Two words: semantic markup.
  3. Many words, with the div + background-image solution:
    1. if the URL turned out to be broken, it would show empty space, with the img + object-fit one, it shows the good old “broken image because of URL” fallback (or alt attribute value).
    2. An img tag is more accessible since we can have alt
    3. Typing src="my-url" is just less characters than style="background-image: url('my-url')".

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.

unsplash-logoNate Bell

Top comments (5)

Collapse
 
cristiannebunu profile image
Cristian N

I haven't really worked on enterprise apps/sites but I can tell you I have ignored ie9 for years for all my css work. And what's more, I am beginning to think that ignoring ie11 might be a good idea as well. Looking at caniuse, I don't think it's a good idea to waste time on making an app/site compatible with old, very low usage versions of browsers.

Collapse
 
hugo__df profile image
Hugo Di Francesco

object fit degrades ok anyways, the image will be stretched, but I remember the days when background-image would result in a blank block in legacy browsers of the day (and you would have to polyfill that)

Collapse
 
naz profile image
Nazim Jamil-Mir

It's not responsive if you are fixing the height and width.

Collapse
 
hugo__df profile image
Hugo Di Francesco

That's true, I guess it still works if one of the height or width isn't fixed (or is a percentage)

Collapse
 
wesnetmo profile image
Wes

MSIE9 is ancient! only "modern" browser having problems with object-fit is MSIE11 afaik, and that's very low in usage anyway.