What Is the CSS Equivalent of HTML "srcset"?

In CSS, you can use the image-set() function as an equivalent to the HTML srcset attribute to create responsive images. image-set() allows you to specify an image set in CSS so that the browser can choose the most appropriate image from the set.

You can use image-set() to specify a set of images (or gradients) to be selected based on resolution or supported formats:

/* select image based on resolution */
background-image: image-set(
  url('image.jpg') 1x,
  url('image-2x.jpg') 2x
);

/* select image based on supported formats */
background-image: image-set(
  url('image.avif') type('image/avif'),
  url('image.jpg') type('image/jpeg')
);

For browsers that do not support image-set(), you can provide a fallback, for example, like so:

.foo {
  background-image: url('image.jpg'); /* fallback */

  background-image: image-set(
    url('image.avif') type('image/avif'),
    url('image.jpg') type('image/jpeg')
  );
}

Please note that for some browsers, you may need to include vendor prefixes. However, the need for vendor prefixes can change over time as browser support evolves. It's a good practice to check current compatibility tables or use autoprefixer tools to automatically add necessary prefixes.


This post was published (and was last revised ) 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.