(Updated: )
/ #CSS #tip #accessibility 

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;
}

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?

  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

Author

Hugo Di Francesco

Co-author of "Professional JavaScript", "Front-End Development Projects with Vue.js" with Packt, "The Jest Handbook" (self-published). Hugo runs the Code with Hugo website helping over 100,000 developers every month and holds an MEng in Mathematical Computation from University College London (UCL). He has used JavaScript extensively to create scalable and performant platforms at companies such as Canon, Elsevier and (currently) Eurostar.

Get The Jest Handbook (100 pages)

Take your JavaScript testing to the next level by learning the ins and outs of Jest, the top JavaScript testing library.