Images
File size
Images are on of the fundamental bulding blocks of the web, you find them everywhere.
Images are also the primary reason why websites are slow. That's because images take space and are rarely optimized properly.
For starters, all your images should be in webp format. It supports transparency and gifs and nowadays, all major browsers support it.
Webp images take way less space than png or jpegs, there really is no excuse for not using them.
Squoosh is a great simple app for optimizing your files. If you want to do bulk upload just do a quick google search, many free services offer it.
Other than the size in kilobytes, your images also have a size in pixel and it's just as important.
Ideally you should resize your images so they are at the same size as they are displayed.
Of course in responsive design, you can't literally do an image for each different device. But you can for example do a version for mobile, one for tablets, one for desktop and one for large screens. Then also a version of each of those 2x for retina displays.
Then you will either use the picture tag or the srcset attribute directly on the image.
Accessibility
If for some reason your users can't see your images, you most likely still want them to have some content.
That's why the alt attribute exists. It must always be present and you should almost always fill it.
The only case where you don't want to fill it is if your images are just icing on the cake and don't convey any meaning.
The simple rule is to say that if the website wouldn't lose any clarity without the image, then you can leave the alt blank.
For all the other cases, here are some rules to follow for your alt-text:
- Keep it short
- Don't start with "An image of...". Your user already knows.
- Go straight to the point. No need to write out every detail.
- If there is relevant text, include it. Ideally text shouldn't be an image at all.
Sometimes you have more to say than fits in the alt text.
For that the solution is very simple, you just add one or more paragraphs describing the image under it.
You can make them sr-only or not, a lot of times, all your users can benefit from more context.
To link the paragraphs to the image, you give the paragraph or the container an id and you reference it in a aria-describedby attribute on the image.
<img
alt="A 1850s painting of a forest by me. Yes I'm that old."
src="/img/painting.webp"
aria-describedby="desc"
/>
<p id="desc">A wonderful description of the painting...</p>