A Look Into: CSS4 Image Set

The emerging trend on HD screens for computer devices has changed the way we build websites, including how we add images. In the past, we can simply use background-image and set the image URL.

Today, this is no longer relevant, since we also need to provide an image that is optimized for higher resolution displays or the image will look pixelated or blurred. So, technically we need two sets of image, one in regular size and another twice the size.

In our previous post, we have discussed using Media Query to serve images in high DPI screen. However, the downside of using this approach is that you need to separate CSS rule for a single selector in different locations. In the case where you have a bunch of background images to insert, things could get too complicated and hard to maintain.

So, in this post, we are going to look at an alternative way of doing this. We are going to look into CSS Image Set.

CSS Image Set Function

CSS Image Set function, image-set(), is classified as CSS Image Level 4. By using this function, we can insert multiple images which will be set for normal and high-res display.

Apart from that, this function is also trying to deliver the most appropriate image resolution based on the connection speed. So, regardless of the screen resolution, if the user accesses the image through a slow Internet connection, the smaller-sized image will be delivered.

At the time of this writing, CSS Image Set is experimental. It is only supported in Safari 6 and Google Chrome 21 and is prefixed — -webkit-image-set().

This function is declared within the background-image property, while the background URL is added within the function followed by the resolution parameter (1x for normal display and 2x is for high-res display), like so.

.selector {
	background-image: -webkit-image-set(url('../img/image-1x.jpg') 1x, url('../img/image-2x.jpg') 2x);

As said, since it is experimental, we need to provide a fallback for the browser that does not support image-set() function. So, we add one background-image at the top, like so.

.selector {
	background-image: url('../img/image-1x.jpg';
	background-image: -webkit-image-set(url('../img/image-1x.jpg') 1x, url('../img/image-2x.jpg') 2x);

We have created a demo page for this code, which you can see from the following links.

Final Thought

image-set() function seems to be a promising solution for serving images in high-res. But, with the current limited browser support, image-set() is not ready to be implemented in a live site. In addition, the implementation could be changed along the way in th enear future. For further reference on this function you can head over to the documentation page at W3C.

Show Comments