search

Home  >  Q&A  >  body text

How can I reserve space for a variable-sized image before it loads to prevent layout changes?

<p>I have an html page with text, image tags and some text like this: </p> <pre class="brush:php;toolbar:false;">This is the text before the image. <img src="image.jpeg"/> This is the text after the image. </pre> <p>Now when the page loads, the text loads before the images since the images take longer to load. So there will be a layout change where the text after the image will immediately follow the text before the image, and if the image hasn't loaded yet, no space will be reserved for the image. However, when the image is loaded, the text following the image moves below, i.e. the layout changes. How can I reserve space for an image before it loads to avoid layout changes? Additionally, any image can be included in the image tag, and the image size is also dynamic. The original size of the image must appear on the page. Also, since I'm using server-side rendering, I know in advance the size of the image I want to display. I cannot fix the height and width of the image as this will cause problems when the image is displayed in a size that changes, the image will no longer fit the size of the screen. </p>
P粉936509635P粉936509635458 days ago600

reply all(1)I'll reply

  • P粉722409996

    P粉7224099962023-08-28 11:19:21

    1- Put your image into a container.

    2- Give the container a fixed width and height, and a fixed min-height and min-width, It can be set according to your needs or the resolution of the picture.

    That's it.

    Don't worry about the js code, I just want to show the image after 3 seconds to help you understand what I mean.

    var image = document.querySelector(".image");
    image.style.display = "none";
    setTimeout(() => {
        image.style.display = "block";
    }, 3000);
    .image-container {
      width: 350px;
      min-width: 350px;
      height: 250px;
      min-height: 250px;
      border: 1px solid red;
    }
    
    .image { 
      width: 350px;
      min-width: 350px;
      height: 250px;
      min-height: 250px;
    }
     <h2 class="before">This is text before</h2>
     <div class="image-container">
      <img class="image" src="https://images2.minutemediacdn.com/image/fetch/w_850,h_560,c_fill,g_auto,f_auto/https%3A%2F%2Fwinteriscoming.net%2Ffiles%2F2021%2F11%2FCaraxes-850x560.jpeg" alt="">
     </div>
     <h2 class="after">This is text after</h2>

    reply
    0
  • Cancelreply