When talking about responsive images we can often be talking about one of two things.
- CSS styling to make an image tag resize itself visually as the browser changes sizes.
- A technique for serving images of differing dimensions dependant on the size of the browser.
Often these techniques are used in unison because the first ensures image are visually the correct size whereas the second ensures that we are not wasting bandwidth by serving really large images to really small devices.
CSS
The first technique is fairly straight forward and can be achieved with the following css:
img { display: block; // Make sure img tag acts like a block level element. max-width: 100%; // Part 1: Set a maximum relative to the parent height: auto; // Part 2: Scale the height according to the width, otherwise you get stretching }
When using bootstrap this can be made even simpler by simply extending the 'img-responsive' class:
img { @extend .img-responsive; }
Markup
The second technique is a lot more involved especially when we factor in content management. The following is markup generated by Drupal from a single source image:
<picture> <source srcset=" /sites/default/files/styles/pod_1x/public/images/pods/clinical_team.jpg?itok=0eSda4ao 1x, /sites/default/files/styles/pod_2x/public/images/pods/clinical_team.jpg?itok=C2Sm4AR1 2x " media="(max-width: 479px)"> <source srcset=" /sites/default/files/styles/pod_1x/public/images/pods/clinical_team.jpg?itok=0eSda4ao 1x, /sites/default/files/styles/pod_2x/public/images/pods/clinical_team.jpg?itok=C2Sm4AR1 2x " media="(min-width: 480px)and (max-width: 767px)"> <source srcset=" /sites/default/files/styles/pod_1x/public/images/pods/clinical_team.jpg?itok=0eSda4ao 1x, /sites/default/files/styles/pod_2x/public/images/pods/clinical_team.jpg?itok=C2Sm4AR1 2x " media="(min-width: 768px) and (max-width: 991px)"> <source srcset=" /sites/default/files/styles/pod_1x/public/images/pods/clinical_team.jpg?itok=0eSda4ao 1x, /sites/default/files/styles/pod_2x/public/images/pods/clinical_team.jpg?itok=C2Sm4AR1 2x " media="(min-width: 992px) and (max-width: 1199px)"> <source srcset=" /sites/default/files/styles/pod_1x/public/images/pods/clinical_team.jpg?itok=0eSda4ao 1x, /sites/default/files/styles/pod_2x/public/images/pods/clinical_team.jpg?itok=C2Sm4AR1 2x " media="(min-width: 1200px)"> <img src="/sites/default/files/styles/pod_2x/public/images/pods/clinical_team.jpg?itok=C2Sm4AR1" width="224" height="224"> </picture>
The picture element works similarly to the video element; a wrapping element contains multiple source elements. This allows the browser to decide which source to use under a certain set of criteria. In the case of the picture element the criteria is set by the 'media' attribute which contains a CSS media query that informs the browser under which circumstances the given source should be used.