Victor Profile picture
Follow if you're interested in UI/UX, development and usability. Weekly UI/UX tips 👉 https://t.co/nsPXcb1DWk Ex founder: @getpulsetic

May 6, 2021, 11 tweets

I bet you don't know how powerful the <img> tag is.

Let's find out 👇

Here is the most simple case of using it.

If the path is correct, the browser will display a picture of the mobile phone.

So far so good.

Now, we forgot to specify the alt tag for better accessibility.

There are two important rules:

1. You should always specify it

2. If the picture serves decorative purpose, you should put an empty alt, so that screen readers don't read it.

If we place an image the way we did, we have two problems:

1. The image will be rendered to its full width and height

2. There will be a layout shift since the browser doesn't know how much space to reserve for the image, until it loads it

So we should specify dimensions.

But what if we want to display different images for desktop and mobile?

This is the so-called "Art direction problem"

For mobile we can:

1. Serve more lightweight image
2. Show cropped version of image focusing on the main aspect

We can solve this in two ways. 👇

The first is using the "srcset" and "sizes" attributes.

srcset: one or more strings separated by commas, indicating possible image sources for the user agent to use.

sizes: One or more strings separated by commas, indicating a set of source sizes.

Another approach is using <picture> tag.

This approach looks much cleaner for me.

What's the difference between these two approaches?

They do the same work, but have a difference:

🔸<picture> dictates what image the browser should use

🔸srcset gives the browser a choice. So this is a recommendation for the browser.

If you have images placed below the fold they will be loaded even if the user hasn't scrolled down.

That will result in huge traffic data loading right away.

To prevent this, you can set the loading attribute to "lazy"

There is also a cool decoding attribute.

When the browser downloads an image it has to decode it first before showing it.

Sync decoding:

text -> image decoding -> image -> text

Async: the image decoding will be deferred and run asynchronously.

So, we started from simple <img src="phone.jpg">.

Look what we have now!

And we didn't work on image placeholders (that's another topic I'll cover later).

Of course, this is a sample snippet, you can have much more sources and different configurations.

Share this Scrolly Tale with your friends.

A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.

Keep scrolling