简体   繁体   中英

Prevent Content Jumping Below Image as it Loads

I currently have an image that I am giving 100% width. The issue I am noticing is that while the image loads, the content below jumps up to where the image sits while it loads. I know I need to give the image some sort of fixed height, but I want the image to remain responsive. The desired effect: The image looks exactly as it does when applying 100% width and prevents the content below from jumping while the image loads. Please advise on this. My code is as follows:

<img src={"https://storage.googleapis.com/youfit-assets/239315_66400_YouFit_JUL21_Mil_Website_1680x761_CarInitial.jpg"}
  alt="travel"
  className="image"/>

Styles:

.image {
  position: relative;
  width: 100%;
  height: auto;
  max-height: 100%;
}

In order to duplicate what I am seeing test on an incognito browser with the following link https://codesandbox.io/s/gifted-montalcini-ohts8?file=/src/App.js

Wrap your img tag into div, so it should look like:

<div className="image-wrapper">
    <img src={...} alt="travel" className="image"/>
</div>
<div style={{ marginTop: 60 }}>TEXT BELOW</div>

then replace your style for image with this style (if your aspect ratio is 4:3):

.image-wrapper {
    position: relative;
    padding-bottom: 37.5%;
}

.image {
    position: absolute;
    width: 100%;
}

or if your aspect ratio is 16:9

.image-wrapper {
    position: relative;
    padding-bottom: 56.25%;
}

.image {
    position: absolute;
    width: 100%;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM