April 3, 2023
In this post we’ll discuss the different techniques to resize images in HTML and CSS. We’ll also explain why to avoid client-side resizing and the benefits of choosing server-side resizing.
When using images on the web it is just a matter of time before you will need to resize them to fit your layout and content. The easiest and most straightforward method is using pure HTML, by using the width and height attributes of the img tag.
Let’s try with an image with an original size of 1456x816
To resize this image to a size of 485x272 pixels we set a height to 272 pixels and width to 485 pixels.
As you can see, this kind of resizing is very easy and straightforward. There are however some major downsides.
HTML resizing doesn’t know about the aspect ratio therefor the aspect ratio of the source image is not maintained. This can result in distorted, stretched images.
When you resize using HTML, it is actually the browser’s that will rescale the image based on what is required. Quality of the resulting image can vary depending the scaling algorithms of the browser.
HTML resizing takes place on the browser. This type of client-side resizing isn’t beneficial for bandwidth usage or loading time. For example serving a 1200x1200 picture and resizing in the browser for a 50x50 avatar isn’t a good idea.
CSS can also be used to set width and height attributes of an image.
As you notice, the CSS size takes precedence over the HTML size attributes. However, it is always advised to provide an width and height to an img tag to avoid layout shift during page load.
When using CSS we can resolve that nasty aspect ratio problem we had with pure CSS.
By declaring a object-fit, we can tell the browser how to fit the image in the given dimensions
The object-fit property can take one of the following values:
More about object-fit can be found here.
To have more control over how the image is placed or cropped in it’s container, you can combine the object-fit with an object-position property.
More about the object-position property can be found here.
Although using CSS gives you a lot more control that using pure HTML, it doesn’t solve the problem of bandwidth, upscaling or downscaling or loading times.
To solve this the recommendation is to use responsive images, or server-side rendering.
When using server-side image resizing, all the processing is done on the server. The client simply request the image in the right size based on the needs and the requirements of the client. This can be done by providing transformation in the URL of the image.