How to use background: url (data: image / png; base64 with Retina?

I noticed that an image embedded in css with a data URI scheme is displayed on Retina screens with "normal" resolution. How to insert an image with the resolution required by the Retina display?

I did not try to embed PNG with double resolution (@ 2) PNG in CSS, but I suspect that it will be displayed in double size, like regular images when the image size is not defined.

+4
source share
2 answers

Two images may have the same resolution, but different dpi. This is an important part in mesh displays, so you need two versions (if you want to keep some bandwidth for those who don't have a retina) of your image with different dpi values.

For more information on how to add a rule to css and some dpi values, see: Retina Display Media Query .

EDIT As a comment from @ carlos-r-balebona noted, the bandwidth will not be saved if you paste the image into CSS, since both versions will always be sent. It will only be saved if you use image URLs, since only the correct one will be downloaded.

EDIT WITH AN EXAMPLE

OK, here is an example:

Suppose you have 2 images (data: image / png; base64, {192_dpi_encoded_image}) and (data: image / png; base64, {96_dpi_encoded_image}).

Now suppose you have a div on which you want to set the background image:

<div id="a" style="width: 100px; height:100px;"> </div> 

And in your css:

 @media only screen { #a { background:url(data:image/png;base64,{96_dpi_encoded_image}); } } @media only screen and (-webkit-min-device-pixel-ratio: 2), only screen and ( min--moz-device-pixel-ratio: 2), only screen and ( -o-min-device-pixel-ratio: 2/1), only screen and ( min-device-pixel-ratio: 2), only screen and ( min-resolution: 192dpi), only screen and ( min-resolution: 2dppx){ #a { background:url(data:image/png;base64,{192_dpi_encoded_image}); } } 

The latest @media with conditions will redefine the background image set earlier only if there is a retina screen, thus setting the image with a large dpi if necessary.

Hope this helps.

+5
source

You can simply set the background size in pixels (the values ​​should be the original sizes divided by two if your image has 2x resolution):

 .element { background-image: url(data:image/png;asdkfasdkf); background-size: 25px 50px; } 
0
source

All Articles