Create performant, responsive, and accessible images for the Web.
Improve Image load time and compatibility.
It is really worth spending the time to get the images right on the web. Poor image strategies are the reason for users' irritation, annoyance, and frustration. A solid image strategy makes your site feel quick and sharp, regardless of the user's device or network connection. After all, Images make the website beautiful so the right image should be shared in accordance with the user's device to achieve the complete motive of using images on the website.
This article will list the main methods and strategies to achieve the following targets:
Give the user the image in the form which fits best to their device screen.
Most optimized image formats should be served to the user as per user device compatibility.
Images should accessible to a wide number of people which also supports social inclusion for people with disabilities as well as others, such as older people, people in rural areas, and people in developing countries.
User device bandwidth would be saved while loading images.
Improve the performance rating of the web page with optimized images.
Optimization of images in multiple ways.
There are also some other unlisted targets that this article will help to achieve indirectly. So let's directly jump into the cream content.
Avoid Image Overflow
This is the most basic and important step toward making an image responsive so that image would not come with a horizontal scroll due to overflow. To avoid image overflow simply use max-width: 100%
. Use the below CSS rule:
width: 100%;
height: auto;
Here height: auto
is also defined to make the image aspect-ratio constant. In CSS frameworks, you can also get premade classes for the above CSS like "img-fluid"
in Bootstrap and "responsive-img"
in Materialize CSS. The same CSS rule can also be used for video, iframe, etc.
Preserve Aspect Ratio
In real-world projects, you would face scenarios like the weird dimension image uploaded by the user from the content management system of your web application. Then, that uploaded image dimension could be much different than your design's default image ratio. As result, there would be a stretched or squashed image that can be seen on the site front. This is because the browser tries to make the image fit as per your design's default image ratio.
To prevent this aspect ratio issue, use object-fit
property:
Use
object-fit: contain
: If you are fine with empty space around the image to preserve the aspect ratio.Use
object-fit: cover
: If you are fine with cropping the image to preserve the aspect ratio. The image quality should be good for this, otherwise, pixels will be blurred.
If your greed is still not fulfilled then use object-position
with object-fit: cover
to adjust crop focus as per your need.
Image Hints
Size Hint
It is better if you give the size of the image in advance so that the browser can reserve the anticipated space to minimize the CLS, in another word's content won't jump while loading.
Example:
<img src="senior_dev.png" alt="description" width="300" height="200">
The above width and height attributes are helping the browser to know width to height ratio of the image. Many companies increase their traffic conversion rate by using these techniques in order to reduce CLS. Especially image hint(defined dimensions) should strictly be provided for the hero image(landing page banner) so that when the user arrives at the landing page he won't see bouncy behavior(image suddenly coming after some seconds and layout re-adjusting).
Priority Hint
Suppose, there is an image that is the first main image to be shown on page load(like a banner image). So, you ask the browser to load it early(as it is an important image) by prioritizing it over other resources(like font files, scripts, etc). To achieve that use the prefetch
, refer to the below code:
<link rel="prefetch" href="banner_img.jpg" as="image" />
Above the fold Image
After the page loads, if the image is shown on the part of the web page before scrolling. Then be eager to load that image using the loading="eager"
in the img
tag. Refer to the code below:
<img src="banner_img.jpg" alt="image description" width="800" height="600" loading="eager" />
Below the fold Image
After the page loads, if the image is shown on the part of the web page after scrolling. Then, you can delay loading that image if it is not of urgent need just after the page load. Therefore, become lazy in loading the image using loading="lazy"
in theimg
tag. Refer to the code below:
<img src="footer_img.jpg" alt="image description" width="200" height="200" loading="lazy" />
After the above code, if the user has scrolled and is about to come to that specific image section then the browser will automatically load the image.
Bonus - Image Sync and Async
In a piece of content, if the image is an important part then prioritize it by using the decoding="sync"
in the image tag. If the surrounding content is more important than the image then use the decoding="async"
in the image tag.
This would be useful in specific scenarios only, but it can make you stand out.
Images for Small Devices
Serving desktop-sized images to mobile devices can use 2–4x more data than needed. If we don't serve small images for small devices then users who are having low bandwidth network on top of small mobile device have to suffer as their browser will download large size HD image which was meant for desktop screens resolutions and is not optimized for small devices (as extra pixels wasted).
So to solve this, just serve multiple versions of the same image as per the user screen size. And use srcset
attribute in img
tag to let the browser know which image to download and at what screen size.
Example
<img src="./senior-frontend-dev.jpg" alt="Image Description"
srcset="./small-senior-frontend-dev.jpg 300w, ./medium-senior-frontend-dev.jpg 600w, ./large-senior-frontend-dev.jpg 1200w"
So basically, you just have to pass different size image URLs in srcset, separated by a comma, and in front of image URL put a screen size. For example, image-medium-url.jpg 600w(1w = 1 pixel) - now the browser will download the medium size image for the device of around 600px size and for that browser will automatically put its that specific image URL in the src
attribute.
- Note:
srcset
is a supportive attribute and not a replacement for thesrc
attribute.
Now the browser will download large images only when needed as per the device size.
How many image versions should you create? - There is no single "correct" answer to this question. However, it's common to serve 3-5 different sizes of an image. Serving more image sizes is better for performance, but will take up more space on your servers and require writing a tiny bit more HTML.
Tip for Accessible Image
If any image in your HTML is not representing any content and is just a presentational image (like an image just to visualize surrounding content). Then, use an empty alt
tag to let the screen reader know that it is a presentational image. But don't try to skip the alt
tag in this case, as an empty alt tag and no alt tag, don't give the same meaning to screen readers.
Well, you should always try to use CSS for displaying presentational images instead of HTML. For that, you can use the background-image
property in CSS.
Which Image Format to choose
Let us make it simple:
For photographic imagery, there are multiple formats that you can choose from like jpg, webp, AVIF, etc. AVIF is the top performer among them then webp is second top but browser support is still low. So better use them with a fallback of jpg.
For non-photographic imagery(like logos, text, or icons), you have two candidates: the Scalable Vector Graphics (SVG) format and Portable Network Graphics (PNG) format. As both allow your images to have transparent backgrounds(as Icons are often used on a transparent background) and work better with areas of solid color. Now, which is better that you will see in the [icons section](# Serve Image Icons Responsively).
But in case you need to preserve fine detail with the highest resolution? Use PNG - PNG does not apply any lossy compression algorithms beyond the choice of the size of the color palette. As a result, it will produce the highest quality image, but at a cost of significantly higher filesize than other formats.
Serve Image Icons Responsively
The first simple tip is that you should use SVG for icons so that they could scale and adapts differently (thus responsive by default).
As SVG doesn't get blurred on scaling like PNG. As SVG is made up of XML code of drawing instructions whereas PNGs (and JPGs, WebP, and AVIF) are bitmap images. Bitmap images store information as pixels. The drawing instructions describe lines and shapes which can be scaled to render at any screen size. Basically, SVG is for images that consist of simple geometric shapes such as logos, text, or icons. They deliver sharp results at every resolution and zoom setting, which makes them an ideal format for high-resolution screens and assets that need to be displayed at varying sizes.
But if there is some complex image(heavy drawing instructions) then use PNG because in case of complex images SVG size increases thus creating heavy download. Remember, if using PNG then get multiple versions of your image in different sizes and use srcset
to deal with the image blur or image oversize issue (download more data without need). As bitmap images do not have the same nice properties of being resolution or zoom-independent —when you scale up a bitmap image you'll see jagged and blurry graphics. As a result, you may need to save multiple versions of a raster image But in SVG you need just one image for all screen sizes(It works!).
How to use icons:
You can use icon images with supportive text or without supportive text. But for better accessibility always try to use supportive text with icons. As icons are presentational images can be served using CSS with <i>
. So using supportive text will help screen readers as screen readers ignore reading presentational images. But if you are not using supportive text with an icon, then serve the icon using the img
tag with the proper accessible name given in the alt
attribute to help screen readers.
Bonus Tip: Embed icons directly icon SVG directly in code to have more control over it like changing the icon color, width, etc, which can't be done if using <img>
tag instead.
Example:
<!DOCTYPE html>
<HTML>
<head>
<style>
.logoutDiv circle {
fill: black;
}
</style>
</head>
<body>
<button class="logoutDiv">
Logout
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg >
<button />
</body>
</html>
So that's it, for now, will meet in the next information-loaded article. It is good to get specialized in the frontend knowledge so please follow and stay tuned for that. Please like and comment, it motivates me to keep creating such stuff. Discord Channel: Senior Frontend Dev - only senior frontend engineers allowed.