Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk10 min

How to Set Image Dimensions to Prevent Layout Shifts

Set image dimensions that describe the real or intended aspect ratio, then combine them with responsive CSS. This guide covers uncropped images, deliberate crops, picture art direction, testing and troubleshooting remaining CLS.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Add accurate width and height attributes to every ordinary image, then make the image fluid with max-width: 100%; height: auto;. The attributes let the browser reserve the correct aspect-ratio space before the file downloads; the CSS lets it shrink on smaller screens. When the design intentionally uses a different crop, reserve that design ratio with CSS aspect-ratio and choose object-fit deliberately.

Why an image can move your page

During the first layout pass, a browser knows an image’s URL but may not yet know the image’s intrinsic dimensions. If the image element has no dimensions and no ratio supplied by CSS, the browser can lay out the heading, paragraph, buttons or other controls immediately after a near-zero-height box. Once the image data arrives, the box expands and everything below it moves. That unexpected movement contributes to Cumulative Layout Shift (CLS), one of the Core Web Vitals.

As an Amazon Associate I earn from qualifying purchases.

The problem is most visible on slower connections, but it is not limited to slow devices. A cached image, a responsive source selected after a media query, a late advertisement, or content inserted by JavaScript can all change the space available after the initial layout. Web.dev reports that 66% of pages have at least one unsized image; the retrieved passage does not state the year of that measurement or an underlying study, so treat it as an indication of how common the issue is rather than a current industry-wide rate.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Image sizing is therefore a layout contract: tell the browser which ratio the rendered box should have before the pixels arrive, and keep that ratio when the box becomes fluid.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

The standard responsive pattern

Put the source dimensions in HTML

Use the real pixel dimensions of the selected source, not arbitrary numbers chosen to make an image look smaller:

<img src="flower.jpg" width="640" height="480" alt="A flower">

The values describe a 4:3 intrinsic ratio. They are hints for layout; they do not force the image to render at 640 by 480 CSS pixels. A browser can use that ratio to reserve space while the image is loading, even when the final display width is controlled by a parent container.

Make the rendered image fluid with CSS

img {
  max-width: 100%;
  height: auto;
}

max-width: 100% prevents the image from overflowing a narrow column. height: auto calculates the rendered height from the intrinsic ratio instead of stretching the bitmap. On a wide screen the image can display near its natural width; on a phone it shrinks to fit while remaining 4:3. Keep the HTML attributes even when a CSS rule sets the width, because the attributes provide the early ratio hint.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use dimensions from the image that will actually be shown

If an optimized derivative, CDN transformation, or responsive source has a different ratio from the original, use the ratio of the presentation that the browser will receive. Substituting a convenient pair such as 300 by 300 for a 640 by 480 image reserves a square and then forces a correction when the 4:3 file loads. The reservation must describe reality, not merely satisfy a validator.

Choosing between HTML dimensions and CSS aspect-ratio

Both techniques reserve space, but they answer different design questions. HTML dimensions express the source image’s intrinsic ratio. CSS aspect-ratio expresses the ratio of the design box, which may intentionally differ from the source because the component crops or contains its media.

Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.
Technique Use it when What controls the ratio Important companion rules
HTML width and height The source ratio is known and should be preserved. The numeric attributes, interpreted as an aspect-ratio hint. max-width: 100%; height: auto; for fluid sizing.
CSS aspect-ratio The component has a deliberate box ratio, a crop, or a non-image container. The CSS ratio such as 16 / 9. Set an appropriate width and use object-fit when the source ratio differs.

Use HTML attributes as the default for editorial images, product photos and other media whose entire frame should remain visible. Use a CSS ratio for cards, hero slots, video placeholders and art-directed components where the slot’s shape is part of the design.

Reserving a deliberate crop with aspect-ratio

Fixed card or hero crop

Suppose a card must always occupy a 16:9 slot, regardless of whether the uploaded photograph is portrait, square or wide:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
img.card-image {
  width: 100%;
  aspect-ratio: 16 / 9;
  object-fit: cover;
}

aspect-ratio reserves the 16:9 height as soon as the element’s width is known. object-fit: cover scales the image until the box is filled and crops the excess. This avoids distortion, but portions of the image can disappear at the top, bottom or sides. Position the crop with object-position if a subject must remain visible.

Contain instead of crop

If every pixel must remain visible, use object-fit: contain with the same ratio. The browser will fit the complete image inside the reserved box, potentially leaving letterboxing. That is a visual choice: it prevents cropping but may show empty bands. Do not apply cover automatically to images where captions, faces, diagrams or product edges are significant.

Do not combine conflicting ratios accidentally

An element with 640 by 480 attributes communicates 4:3, while a rule assigning aspect-ratio: 16 / 9 communicates a 16:9 box. The CSS design ratio can be intentional, but you must also decide whether to crop or contain the source. If neither is intentional, remove the conflicting rule and preserve the source ratio with height: auto.

Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

Responsive images and art direction

Same subject, different resolutions

With srcset and sizes, a browser can select a smaller or larger file for the current viewport. If all candidates share the same crop and aspect ratio, one set of width and height attributes can describe that ratio while the browser chooses the appropriate resolution.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<img
  src="flower-640.jpg"
  srcset="flower-640.jpg 640w, flower-1280.jpg 1280w"
  sizes="(max-width: 700px) 100vw, 640px"
  width="640"
  height="480"
  alt="A flower"
>

The numbers in srcset are candidate widths; the 640 by 480 attributes still express the shared 4:3 ratio. Keep the ratio consistent across candidates unless the design changes deliberately.

Different crop at a breakpoint

Art direction uses <picture> when a phone and a desktop need different framing rather than merely different resolution:

<picture>
  <source media="(max-width: 700px)" srcset="flower-portrait.jpg" width="480" height="640">
  <source srcset="flower-landscape.jpg" width="1280" height="720">
  <img src="flower-landscape.jpg" width="1280" height="720" alt="A flower">
</picture>

The selected presentation can have a different ratio at each breakpoint, so reserve the ratio that belongs to that presentation. Modern Chrome, Firefox and Safari support width and height on <source> elements in <picture>, according to web.dev’s guidance. Test the breakpoints you support, because a mismatch between the reserved box and the selected crop can still produce a correction during loading.

Implementation checklist for existing pages

  1. Inventory image elements. Include content images, thumbnails, logos, avatars, background-like media implemented with <img>, and images injected by components. Do not limit the audit to the largest hero.
  2. Record the intended presentation. For each image, decide whether the entire source should remain visible, whether the box should crop, and whether the ratio changes by breakpoint.
  3. Add accurate attributes. Put the source or selected presentation’s intrinsic dimensions in width and height. Use the actual ratio, not the current CSS pixel size.
  4. Apply fluid rules. For uncropped images, use max-width: 100%; height: auto;. Scope component rules so a card crop does not unexpectedly affect editorial images elsewhere.
  5. Define intentional boxes. Add aspect-ratio to a crop slot or placeholder whose design ratio is known. Pair it with object-fit: cover or contain according to the visual requirement.
  6. Check responsive sources. Confirm that every srcset candidate keeps the expected ratio, or that each art-directed <source> communicates its own ratio.
  7. Inspect the loading sequence. Throttle the connection, reload with the cache disabled, and watch the area below each image. The heading, text or control should start in its final position before the image appears.
  8. Run Lighthouse and field monitoring. Lighthouse can identify unsized images in a lab run. Real-user CLS can differ because of viewport sizes, cached resources, ads, personalization and later interactions, so use field data when movement occurs only for some visitors.

Diagnosing a layout shift that remains

The image still expands

Inspect the element in developer tools while the page is loading. Check whether the final image is the element you sized, whether a framework replaced it with another node, and whether a CSS rule sets height: 0, height: auto on a box with no usable ratio, or an overriding width. Verify that the attributes contain numbers and that a responsive source was not assigned a different crop.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.

The image is stable but text moves

Images are only one CLS source. Videos, advertisements, embeds, web fonts and content inserted after the initial layout can move the same text. Give video and iframe-like embeds a known ratio, reserve an appropriate minimum height for late modules when an exact size is unavailable, and make ad slots occupy their expected space before an ad response arrives. For a dynamically inserted component, render its shell with the final dimensions before appending its content.

Movement appears only after interaction or navigation

CLS is concerned with unexpected movement in the page’s lifecycle, not just the first paint. A carousel that changes height, an image gallery that replaces a portrait with a landscape frame, or a “load more” action that inserts content above the viewport can all create shifts. Give each state a stable box or place new content below the user’s reading position. If the movement is intentional and directly follows a user action, it may be treated differently by CLS scoring, but a stable design is still easier to use.

The lab score is good but field CLS is poor

A basic Lighthouse load may finish before a personalized recommendation, consent panel, ad, or font swap appears. Compare field measurements by route, device class, viewport and connection. Reproduce the worst flow with the same late resources, then reserve space for the component that arrives late. Do not assume that adding dimensions to the largest image fixes every field report.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Common mistakes and their fixes

  • Leaving dimensions off because CSS is responsive. Responsive CSS controls the final size; HTML dimensions provide the early ratio. Use both.
  • Using arbitrary square attributes. A square reservation for a landscape source creates its own correction. Measure the source or define an intentional crop.
  • Setting a width but not a height. A lone width does not give the browser enough information to reserve the vertical space. Supply both dimensions or a CSS ratio.
  • Hard-coding a desktop pixel height. A fixed height can distort or clip a fluid image on small screens. Prefer the intrinsic ratio, or use a documented component ratio with fitting behavior.
  • Stretching with width: 100%; height: 100%;. Unless the box ratio matches the source, this distorts the image. Use height: auto, cover or contain.
  • Assuming lazy loading reserves space. Lazy loading changes when a resource is fetched; it does not by itself tell the browser how tall the element will be. Size the element independently.
  • Ignoring generated markup. CMS templates, markdown renderers and JavaScript components may omit attributes even when hand-written examples include them. Fix the template or component so every instance receives dimensions.
  • Forgetting accessibility while editing markup. Keep a meaningful alt description for informative images and an empty alt for decorative ones. Layout stability is not a reason to remove alternative text.

How the browser uses the numbers

The HTML attributes establish an intrinsic aspect ratio before the image bytes arrive. If the layout gives the element a width of 320 CSS pixels and the attributes describe 640 by 480, the browser can calculate a 240-pixel height during the initial layout. When the file loads, the bitmap fits that reserved rectangle, so content below it has no reason to move.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The attributes do not request a 640-pixel download, guarantee a 640-pixel display, or replace responsive image selection. They are metadata about proportions. The final rendered dimensions still depend on the containing block, CSS, device pixel ratio, and the candidate chosen by srcset.

Testing dimensions in production conditions

Visual test

Open a page in a private window, disable the cache in developer tools, throttle the network, and reload from the top. Watch the first viewport and then scroll through lazy-loaded content. Repeat at a narrow phone width, a tablet width and a wide desktop width. Check both portrait and landscape art-directed sources.

Automated test

Run Lighthouse on representative URLs and inspect the diagnostics for image elements without explicit dimensions. Treat the report as a starting point: a page can pass a lab audit while a later embed or ad shifts content in the field. Keep a record of the affected URL, viewport and component so a regression can be traced to a template change.

Field test

Use real-user monitoring to segment CLS by page type and device. Investigate sessions with late shifts rather than averaging them away. A field problem limited to one campaign slot or one breakpoint often points to a missing reserved box in that component, not to every image on the site.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Decision guide

  • Image should display uncropped: add the source’s accurate width and height, then use max-width: 100%; height: auto;.
  • Image belongs in a fixed-ratio card: set the card’s aspect-ratio, make the image fill it, and choose cover only if cropping is acceptable.
  • Image changes crop at a breakpoint: use <picture>, describe each selected presentation’s ratio, and test every breakpoint.
  • Ratio is unknown until runtime: reserve a conservative box or minimum height for the late content, then replace it without changing the surrounding layout once dimensions are known.
  • Movement persists after image fixes: audit video, ads, embeds, fonts and script-inserted content; image attributes cannot reserve space for unrelated elements.

What success looks like

On a throttled reload, the text and controls below an image occupy their final positions immediately. The image may arrive later or at a different responsive width, but it scales within the reserved ratio. A card crop remains the chosen shape without distortion, and an art-directed source changes framing only at the intended breakpoint. Lighthouse no longer flags unsized images, while field monitoring confirms that remaining CLS comes from identified components rather than unexpected image expansion.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.