Jamie Sefton | Web Developer

Retina Inline Images with srcset

Posted: 12th Jan 2015

Retina Inline Images with srcset

With mobile devices and even now desktop screens becoming retina quality it is becoming important to display higher quality images on the correct screens. Retina quality is generally known as being twice the pixel density of a standard image. So most people deal with this by making the retina version twice the original size.

For example, if your logo is 200px X 100px, then your retina versionw ould be 400px x 200px.

There are 2 methods of usnig retina images in your code. The first being through CSS and using hte image as a background image. You can easily replace a background image with an alternative. You can use a media query to check the pixel ratio of the current device, then swap out the images.


@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi){ /* Swap images for Retina versions here */ .logo{ background-image:url('./logo@2.jpg'); background-size: 200px 100px; } }

Note that the background-size has been set to the original image size. This is because Retina needs to squeeze 2 pixels into every 1 pixel. This is achieved by forcing the double size image into half it's size of space.

The main issue with using background images is that you need to set the width and height of the element in order for the background image to come through. This can prove the be an issue when you are building a fluid / responsive website.

Using HTML5 and setsrc

Another alternative to using CSS is by using HTML5. This will allow you to set the retina version for your current image you are using within an IMG tag.

You will still need to create another version of your logo which 2x the original size. You then apply this image to your image tag like in the example below:

<img src="./logo.jpg" srcset="logo@2.jpg 2x" />

What this will do is basically serve the none retina image on any browser that doesn't support the HTML5 setsrc. Then on browsers that do it will allow you to apply a different graphic based on what you have asked it to show. So in the example above, it is showing an image that is 2x the original.

Setsrc is a powerful tag that can be used to do much more than just retina images. You can also use it like a media query and show different images based on screen width and orientation