2

I want to prevent page-reflow, caused by image loading on a web page.

Page reflow occurs when images load after the page's text content has already rendered. There's a 'jerk' caused by the said page-reflow. It makes for awful user experience.

My requirements are:

  • (i) All images be fully responsive
  • (ii) Have a max-width of 450px (while maintaining aspect-ratio)
  • (iii) Be center-aligned within their containers

There can be several images on the page. All have different aspect ratios (but scaled to the same width - i.e. 450px). I know their dimensions beforehand.


Currently my code is simply:

    .container {
          text-align:center;
          overflow:hidden;
          background:whitesmoke;
          border-top:1px solid #F0F0F0;
          border-bottom:1px solid #F0F0F0;
        }
    
.container img {
          width:100%;
          max-width:450px;
          vertical-align: top;
        } 
    <div class="container">
    <img src="https://s3.ap-southeast-1.amazonaws.com/damadam-2019/public/31a1b420-59c9-405a-a197-e04dd1e2eaf9.jpg" alt="image">
</div>

This fulfils all my requirements - except it can't prevent page reflow. How do I tweak this to get my desired result?


Traditional solutions to prevent such page-reflow go something like this:

HTML

<div class="container">
  <img src="https://s3.ap-southeast-1.amazonaws.com/damadam-2019/public/31a1b420-59c9-405a-a197-e04dd1e2eaf9.jpg" alt="image">
</div>

CSS

.container {
  display: block;
  position: relative;
  padding-bottom: calc(100%/(450/562));/* example width=450px height=562px*/
  height: 0;
}

.container img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
} 

This works fine. But it doesn't impose a max-width like I need it to. The image fills the entire container - as large as that container is (e.g. the full width of the screen on a laptop).

To tweak it, I tried adding max-width:450px;max-height:562px in .container img. That corrected the image's dimensions. But it gave the container extra padding at the bottom:

enter image description here

That's a shame. What I really wanted was for it to look like below:

enter image description here

Note that the gray colouration above is the background container, which simply disappears on smaller resolutions:

enter image description here

What's the best way for me to achieve my requirements? An illustrative example would be great.

Note: adding max-width: 450px;max-height: 561px; in .container doesn't solve the problem either.

Hassan Baig
  • 15,055
  • 27
  • 102
  • 205

0 Answers0