Use HTML5 To Achieve Responsive Image

August 28, 2022 0 Comments

Responsive design can stay here, but there are a lot of problems to solve when it comes to making images responsive. Although responsive images automatically adapt to the size of the window, a problem for users is that the point of agreement of the image becomes barely visible when the image becomes too small.

The ideal consensus among web developers is that the Real Dimension should also react. The browser should be able to load smaller or larger images depending on the size of the window. In this way we can control and provide the best part of the image instead of the shrunken image. This is where the HTML5 image element comes into play. The image allows us to provide several image sources and to control the broadcast through multimedia requests.

First Steps

I have prepared an image in three different dimensions as follows. The image has been cropped to maintain focus on the person in the image. The plan here is that we display the smaller size on small screens and the larger image on large screens.

Using an image element

Picturefill can work in two ways: we can embed srcset in the img tag or use the picture element. Here we will choose the image element, because it is more convenient, easier to understand and more readable. As with video and audio elements, picture encapsulates several source elements that point to the source of the image as follows.

As you can see in the code snippet above, the source element is defined using the Media attribute. In this Attribute, we specify the breakpoint of the window on which the image should be represented. You can see the effect immediately.
Look at the demo page and resize the window. You need to find the displayed image in the specified window width.

Supported browser

Every browser now supports the HTML5 image element, including Microsoft Edge and the mobile browser. However, if you need to support older browsers, such as Internet Explorer, which do not support this element, you can use a Polyfill, Picturefill.

Picturefill is a JavaScript library developed by Filament Group. This allows us to use the image element now. First, upload the script to the Github repository and paste the image fill.js or picturefill.minute.js. You can just put it in the Head tag.

Last Thought

The image element is a great addition in HTML5. It offers more control over the size of the image that the browser should display in a given window size. The image element works in all current browsers and WordPress has integrated it since WordPress 4.4. If you already need to support older browsers like Internet Explorer that don’t support the image element, you can customize it with Picturefill.

Leave a Reply

Your email address will not be published. Required fields are marked *