To enable browsers to automatically select the most suitable CSS background-image
depending on resolution, you can use the CSS image-set()
function. This function allows you to offer multiple image choices, and define their corresponding resolutions using the CSS <resolution>
data type:
background-image: image-set(
url('image.jpg') 1x,
url('image-2x.jpg') 2x
);
With this, the image-set()
function allows the browser to select the most appropriate image (from the provided set of images) based on the user's device pixel ratio (DPR). If the user's DPR matches one of the specified values, that image is used. Otherwise, the browser chooses the closest match.
If you wish to support browsers that do not support image-set()
, you may have to add vendor prefixes and/or include a fallback before the "image-set()
" declaration.
For example, you can add a fallback before the "image-set()
" declaration in the following way:
.foo {
background-image: url('image.jpg'); /* fallback for browsers that do not support `image-set()` */
background-image: image-set(
url('image.jpg') 1x,
url('image-2x.jpg') 2x
);
}
This ensures that browsers that do not support image-set()
will still display the background image as expected.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.