Issue
I have been making changes to make my site more responsive and, in general, this has gone well. However, I have run into one problem:
Before, I always used height and width attributes on img elements in order to reserve space in the layout for the images while the browser loads them in. This prevents the layout from jerking around while the browser loads and calculates the needed space for the image.
After making my images more responsive, however, by using max-width: 100%
and taking out the height and width attributes, the browser no longer reserves space for the image (because it no longer knows how tall or wide the image is going to be in advance since I couldn't explicitly tell it)
My goal is to have responsive images that also take up their appropriate space in the page layout upon its initial load. Does anyone know of a solution for this?
*EDIT (SOLUTION) - this is the best article I have found on the topic. Nice approach!
Solution
The correct answer here is to prevent the vertical reflow by using the "padding-bottom trick". To make this technique work, you must know the proportions of the image in advance.
Thanks to Anders M. Anderson for posting an excellent article on the topic. This is how it works:
- Wrap your images in a div with a class of image-container (or similar), and provide the appropriate styles (below)
- Secondly, style your images with absolute positioning and force them to fill the space of the container
- Lastly, add another class to the image-container div according to the aspect ratio of the image. This aspect ratio class forces a padding-bottom onto the parent div, giving the container the correct height, and allowing your image to take up the expected space.
NOTE, if you're wondering why my class names (below) look weird, check out "BEM", it's great.
.responsive-image__container {
position: relative;
height: 0;
overflow: hidden;
background-color:black;
}
.responsive-image__img {
position: absolute;
top: 0;
left: 0;
width:100%;
}
.responsive-image__container--ratio-16-9 {
padding-bottom: 56.25%; /* 9/16*100 */
}
.responsive-image__container--ratio-4-3 {
padding-bottom:75%; /* 3/4*100 */
}
.responsive-image__container--ratio-1-1 {
padding-bottom: 100%; /* 1/1*100 */
}
/* and so on, for any aspect ratios you need to support */
<div class="responsive-image__container responsive-image__container--ratio-4-3">
<img src="http://placekitten.com/400/300" class="responsive-image__img">
</div>
Note, this also works for embedded videos which need to be responsive... AND take up their appropriate height in the browser to prevent content reflow, which is the entire point of this technique.
Answered By - Brian FitzGerald
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.