The @DVD answer already answers your question. But as this is a very broad and discussed subject (including I am very interested in a standard solution) I will leave an alternative that I hope will soon be adapted for all browsers.
The tag <picture>
of Html5
This new tag allows us to treat images the same way we treat the tag <audio>
, where we can put various formats to work on different types of browsers.
In it, we can use the attribute media
with the same syntax as when we use @media-queries
in CSS, to display an image relative to the screen size.
See this example (resize the screen) also has on Jsfiddle:
picture, img {
width: 100%;
height: auto;
}
<picture>
<source srcset="https://vidanimal.com.br/wp-content/uploads/papillon.jpg" media="(max-width: 700px)" alt="Pequeno">
<source srcset="https://www.blupet.com.br/uploads/pets/26984/2698418092017185025000000.jpg" media="(max-width: 1024px)" alt="Medio">
<img srcset="https://www.ultracurioso.com.br/wp-content/uploads/2015/07/sao-bernardo.jpg" alt="Grande (imagem fallback padrão)">
</picture>
When resizing the screen will be shown the image corresponding to the @media-querie
you defined in the attribute media
, in it you can use the attributes max-width
, min-width
, max-height
, min-height
, orientation
among others that are in accordance with the syntax of @media-queries
.
In the tests I did worked on Chrome(v61), Firefox(v55) and Opera(v48), in IE11 I had to add another line in the tag <img>
standard with a src
to be able to function, it was like this:
<img src="https://www.ultracurioso.com.br/wp-content/uploads/2015/07/sao-bernardo.jpg" srcset="https://www.ultracurioso.com.br/wp-content/uploads/2015/07/sao-bernardo.jpg" alt="Grande (imagem fallback padrão)">
This worked for the other navigators I mentioned without giving conflict.
You can see the support for this tag on Can I Use and use it if you see it coming to mate, and still if you are not sure there is a JS plugins called Picturefill that promises to be fine crossbrowser
and uses the same syntax I showed.
The answer was a bit big, but if someone has a suggested edit just comment.
Sources: Webdesign.tutsplus, Google ;) and Smashing Magazine.
How are you using the
.each()
it will go through each image with the class you specified and apply the image correctly, however I believe there are other better ways to do this.– Bruno Romualdo
Which would be @Brunoromualdo?
– AntonioSantos