How to Stop Mobile Layout Shifts Caused by Lazy‑Loaded Images
This article explains why images that load after the DOM cause noticeable layout jumps on mobile pages and presents four CSS‑based solutions—media queries with pixels, rem units, viewport‑based vm units, and percentage padding—along with a complete example that eliminates the shift.
When images are loaded after the DOM finishes, mobile pages often show overlapping content at first and then jump noticeably once the images appear.
Several CSS techniques can solve this problem:
Media query + px
@media screen and (max-width: 320px) {
img {
height: 50px;
}
}rem
img {
height: 0.5rem;
}vm
Use the smaller of viewport width or height, divided into 100 units, as the vm unit (not supported on iOS 8‑ and Android 4.4‑).
percentage padding Padding can be set in percentages, which are calculated relative to the width of the containing block (margin behaves similarly). See the W3C padding‑properties specification.
/* Example layout */
* {
margin: 0;
padding: 0;
}
ul {
overflow: hidden;
}
li {
width: 50%;
float: left;
text-align: center;
}
img {
width: 100%;
}Using a pseudo‑element instead of an extra div for the child element, the image is positioned with padding‑top: 100% to keep a 1:1 aspect ratio:
.cover {
position: relative;
font-size: 0;
display: inline-block;
width: 100%;
}
.cover img {
width: 100%;
height: 100%;
position: absolute;
left: 0;
top: 0;
}
.cover:after {
content: '\20';
padding-top: 100%;
display: block;
}Resulting layout prevents the page from jumping when images load. The final effect is shown below:
For images with other aspect ratios, adjust the padding-top value accordingly (e.g., 50% for a 2:1 width‑to‑height ratio).
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
JavaScript
Provides JavaScript enthusiasts with tutorials and experience sharing on web front‑end technologies, including JavaScript, Node.js, Deno, Vue.js, React, Angular, HTML5, CSS3, and more.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
