As of WordPress 4.4, there is native responsive image support via srcset and sizes in WordPress. If you are unfamiliar with these image attributes, here is a good description of the srcset and sizes attributes in WordPress.
Using srcset and sizes allow the browser to find the best image size to load. While this is great for displaying a different size image, it does not have the capability of showing a completely different image at different sizes. This is where the picture element comes in.
Using the following code as an example, we can specify an entirely different image depending on screen size.
1 2 3 4 5 6 7 8 | <picture> <!--[if IE 9]><video style="display: none;"><![endif]--> <source srcset="http://example.com/wp-content/uploads/2015/11/slide1.jpg" media="(min-width: 1120px)"> <source srcset="http://example.com/wp-content/uploads/2015/11/slide1-1120x432.jpg" media="(min-width: 900px)"> <img srcset="http://example.com/wp-content/uploads/2015/11/slide1-small.jpg" alt="example Slide"> <!--[if IE 9]></video><![endif]--> </picture> |
How Does this work?
If you look at the above code, you can see that the image starts by using “slide1-small.jpg”. Once the browser reaches a size of 900px, the image is swapped. A higher resolution image swapped again at a browser width of 1120px.
Of course, not all browsers support the picture element, so the Picturefill polyfill should be included.
-0 Comments