Web Solutions Point

This blog is all about sharing solutions

Free Advertisement

Friday, March 2, 2018

Fluid image containers to prevent webpage from lagging


In this article, i will show you some hacks to prevent your web page from lagging. The problem is when you have to many images in your web page, your content shift downwards as soon as the image gets loaded and this will irritate your audience. This happens because browser don’t know that how much space a image will occupy & when image gets loaded into browser it will shift your content downwards.

here is the problem


To solve this problem, we will tell browser that you have to leave a perfect space for image. To find out how much space the image will occupy, we must know the height & width of the image. By the help of height & width we will calculate the aspect ratio of image. Then we will assign padding to image wrapper in percentage. 

The formula to find padding is given below
Padding Bottom = (Image Height / Image Width) * 100%
In my case, the image size are 1920 x 1200 px. So, the padding should be

Padding Bottom = (1200 / 1920)  * 100%

Padding Bottom = 62.5%

To make your web page responsive we will assign the padding in percentage, so that it can leave a perfect space in every resolutions.

We also need to assign position: absolute to the image, and position: relative to the wrapper, to ensure the padding is not added to the height of the image when the browser calculates the wrapper's height.

The final results after this hack


Example:

1. HTML

2. CSS

.image-wrapper {
    position: relative;
    height: 0;
    padding-bottom: 62.5%;
    border: 2px solid #dadada;
    margin-bottom: 5px;
}
.fluid-image {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

No comments:

Post a Comment