Responsive Image Placeholder With Pure CSS

css , html , responsive

It looks too bad when a page contains too many images and the height of the page keeps changing while those images load. Once in a while every front-end developer needs to deal with responsive images and to show them to the user in the most optimal way.

Problem:

One of the biggest challenges faced by a developer is to show image placeholder while the image is loading. One most common way is to use javascript but for doing such a basic task it is an overkill.

Solution:
<div class="image-box">
        <img src="/test.jpg" />
</div>
.img-box {
        height: 0;
        background: #eee;
        position: relative;
        padding-bottom: 50%;
}
.img-box>img{
        width: 100%;
        height: 100%;
        display: block;
        position: absolute;
}
Explanation:

Suppose we want to show an image having a width twice that of the height i.e. the ration of width to height is 2:1. In simple words we can say that height is 50% of the width of the image. So, we create a image container which has no height but padding-bottom of 50%. Now as the img-box has not height we place the image inside this container with position absolute and width/height of 100% so that it covers the whole container.

The trick here is that when we define padding in terms of percentage, It is calculated in reference to width of the box. Hence img-box will have a height half that of the width. You can change the padding-bottom to any percentage depending on the ratio of the image.

Tip:

You can change the background of the img-box to a loading icon as well which will give the feedback to the user that the image is loading.