Sizes Attribute
HTMLThe sizes attribute is an HTML hint used with responsive images to indicate the expected rendered width (the slot size) in CSS pixels under different viewport conditions. Paired with width (w) descriptors in srcset, it enables the browser to choose an appropriately sized image before layout completes, avoiding unnecessary downloads and upscaling. sizes is evaluated from a list of media conditions and lengths, applies to both img and picture/source, and is ignored when srcset uses density (x) descriptors.
Definition and role
In responsive images, the sizes attribute provides the browser with width hints that reflect how wide an image will render at various viewport breakpoints. This width is the slot size: the final CSS pixel width the image occupies after layout. Because the network request for the image is often initiated before full layout, sizes supplies the information the browser needs to select an appropriate resource early.
sizes is written as a source size list: a comma-separated sequence of media conditions followed by lengths, with the first matching condition determining the slot size. A final, unconditional length typically acts as a fallback. The attribute appears on img elements and on source elements inside picture, allowing different slot-size rules per art-directed source if needed.
When used with srcset width (w) descriptors, sizes enables the browser to compute an ideal intrinsic pixel width (slot size multiplied by device pixel ratio) and pick the smallest candidate that meets or exceeds that requirement. Without these hints, the browser risks fetching a file that is too large for the layout or too small for the device’s pixel density, harming visual quality or performance.
sizes does not change layout. CSS still controls how big the image renders; sizes merely describes the expected result in a form the browser can use before layout stabilises. This distinction is central to how responsive images achieve both visual correctness and efficient loading.
How sizes interacts with srcset descriptors (w vs x)
Width descriptors (w)
With w descriptors, each candidate indicates its intrinsic pixel width (for example: 400w, 800w, 1200w). The browser evaluates sizes to estimate the slot size in CSS pixels, multiplies by the current device pixel ratio (DPR), then chooses the smallest candidate width that is greater than or equal to that number. If none meets the threshold, it selects the largest candidate available.
Density descriptors (x)
With x descriptors (for example: 1x, 2x, 3x), the browser ignores sizes. Selection is based on DPR alone, picking the closest density not less than the device’s current DPR. This mode suits images that render at a fixed CSS size across breakpoints, such as icons or logos, where density scaling provides crispness without multiple width variants.
Mixing and picture interactions
A single srcset cannot mix w and x descriptors. Inside picture, each active source can use either w or x, and its own sizes if w is used. The media attribute on source determines which source is active; sizes then informs selection within that active source’s srcset when w descriptors are present.
Selection outcomes and quality
With w+sizes, quality is governed by how accurately sizes mirrors layout and the spacing of candidate widths. Too few widths can force an oversized pick; too many can add build complexity without tangible wins. With x, quality tracks DPR, but if the CSS size changes across breakpoints, density-based selection can miss ideal widths and waste bytes.
Syntax and length units
Source size list grammar
sizes="<source-size-list>" consists of comma-separated items. Each item is either "<media-condition> <length>" or a bare "<length>" as a fallback. Items are evaluated left to right; the first with a true media condition determines the slot size. A final fallback length is strongly recommended to cover all cases where no media condition matches.
Length types and calc() support
Allowed lengths are CSS absolute and relative lengths such as px, em, rem, vw, vh, vmin, vmax, ch, and calc() expressions combining these. Percentages are not permitted. Viewport-relative units are common for fluid layouts (for example: 50vw), while px expresses fixed slots (for example: 320px). calc() allows clamping patterns like min(100vw, 1200px).
Media conditions and breakpoints
Media conditions mirror CSS media queries (for example: (min-width: 60rem)). Because sizes is evaluated before layout, conditions should depend on viewport features, not container sizes. Typical patterns mirror your CSS breakpoints so that the slot-size hint aligns with the layout rules that eventually apply.
Overview
The sizes attribute exists to close the information gap between when the browser begins fetching images and when layout determines the element’s real size. By declaring how wide an image is expected to render at a set of viewport breakpoints, it lets the browser fetch the best-fitting candidate with minimal delay and waste.
For fluid designs, sizes commonly uses vw-based values that track the viewport and cap growth for large screens. For example: (min-width: 1200px) 800px, (min-width: 768px) 50vw, 92vw. In fixed or bounded contexts like sidebars, px-based slots make sense, such as 320px or 240px, to avoid picking unnecessarily large resources on wide viewports.
sizes is complementary to CSS. It does not set width; it reflects it. It also complements width and height attributes that establish intrinsic aspect ratio to prevent layout shifts. When both are present, the browser can reserve the right space, select a well-sized resource, and render the image crisply on high-DPR devices.
Because srcset selection happens per active source in picture, sizes can be specified on each source to provide accurate slot hints for art-directed crops at different breakpoints. The img element should still include a sizes fallback for cases where no source matches or the browser does not support picture features.
What it does for performance
Accurate sizes reduces over-downloading by preventing the browser from fetching an image wider than the slot requires. For example, if the slot is ~360 CSS px on a 2x screen (effective need ≈ 720 px), choosing a 720w candidate instead of a 1200w candidate can cut transferred bytes by roughly 40–60% depending on format and compression settings, with no visible quality loss at typical viewing distance.
Selecting the right resource early improves Largest Contentful Paint for hero images and above-the-fold content by avoiding late re-fetches or decoding oversized files. It also reduces cumulative memory use and decode time on mobile devices, which can otherwise struggle with very large bitmaps even if they are downscaled for display.
The preload scanner benefits when sizes is present, especially if you also declare imagesizes on link rel=preload for critical images. Matching sizes and imagesizes ensures the preloaded candidate aligns with what the parser would select, avoiding wasted early downloads and ensuring consistent cache hits across navigations and hydration states.
At the same time, aggressive or inaccurate sizes values can under-specify the slot, leading to visible blurriness on high-DPR screens. The practical performance win therefore depends on mirroring real layout and offering a sensible spread of width candidates that bracket the expected needs without creating unnecessary variants.
Defaults when sizes is omitted or invalid with width (w) descriptors:
When srcset uses w descriptors and sizes is omitted, the HTML specification defines a default source size of 100vw. In practice, the browser assumes the image will render the full viewport width and picks a candidate accordingly. On pages with narrow content columns or small inline images, this default often yields selections far larger than necessary, increasing transfer size and decode cost.
If sizes is present but invalid, the parser discards malformed items and falls back to the last valid item; if none remain, it behaves as if sizes were absent and uses 100vw. Minor syntax issues—such as missing a unit or unmatched parentheses in a media condition—are enough to invalidate an item, so production build tooling that validates sizes strings is helpful.
The 100vw default applies regardless of picture, though picture’s media attribute still determines which source is active. For sets that use x descriptors, sizes is ignored entirely, so omission or invalidity does not affect selection. However, if a layout is fixed-width or tightly constrained, density-based srcset or an explicit px size in sizes avoids the 100vw pitfall.
Implementation notes
- - Mirror CSS breakpoints. Keep sizes media conditions aligned with the breakpoints that control the image’s container width. If the layout changes at 768px and 1200px, reflect those thresholds in sizes to minimise mismatch between hinted and actual slot sizes.
- - Clamp wide screens. Use calc() or min() to cap 100vw on large desktops (for example: (min-width: 1200px) 1200px, 100vw) so the browser avoids picking ultra-wide assets when the design limits content width.
- - Prefer w+sizes for fluid content images and x descriptors for fixed-size UI assets. Do not mix descriptor types in one srcset. For picture, place sizes on each w-based source and on the img fallback.
- - Pair with width and height attributes to establish intrinsic aspect ratio and prevent layout shifts. sizes does not influence layout; the intrinsic dimensions do.
- - Preload critical images with imagesrcset and imagesizes on link rel=preload to match the runtime selection. Otherwise, the preloaded candidate can differ from what the parser would pick.
- - Be mindful of viewport units. 100vw includes scrollbars in many environments, which can cause slight over-selection. Clamping with min(100vw, Npx) is a practical mitigation.
Comparisons
w + sizes vs x descriptors
- - w + sizes: Best for fluid content where slot width varies across breakpoints. Provides precise control and avoids overshoot. Requires more variants and careful hinting.
- - x descriptors: Best for fixed-size UI elements. Simpler authoring and selection based on DPR. Can waste bytes if the element’s CSS size changes with the viewport.
sizes vs CSS-only approaches
- - CSS alone controls rendering size but does not guide network selection. sizes bridges that gap so the browser can fetch an appropriately sized resource immediately, rather than downloading a generic large image and downscaling it.
sizes in picture vs media on source
- - media on source chooses which source is active (for art direction or format switching). sizes then guides candidate selection within the chosen source when w descriptors are used.
FAQs
Do I need sizes when using x descriptors in srcset?
No. When srcset uses x descriptors, the browser selects a candidate based on device pixel ratio and ignores sizes. sizes only participates in selection when srcset uses w descriptors. If your image’s CSS size varies significantly across breakpoints, prefer w descriptors with sizes instead of x to avoid over- or under-fetching.
Can I use percentages in sizes?
Percentages are not allowed in sizes. Use viewport-relative units like vw for fluid widths or px for fixed widths. calc() is supported, so patterns such as min(100vw, 64rem) or calc(50vw - 1rem) are valid and useful for reflecting real layout constraints and gutters.
Where should sizes go when using picture?
Place sizes on each source that uses w descriptors, tailored to the art-directed layout for that source, and also on the img fallback. The media attribute on source controls when a source is active; sizes informs selection within that source’s srcset once active. If a source uses x descriptors, omit sizes from that source.
How many width candidates should I generate for w-based srcset?
A practical approach is to cover the expected slot range with 5–8 widths spaced by roughly 1.25–1.5x steps (for example: 320, 480, 640, 800, 960, 1200). Extremely dense sets yield diminishing returns and can increase build time and storage. Ensure the largest candidate meets your maximum hinted slot size times the highest realistic DPR you intend to support.
Does sizes account for scrollbars, zoom, or dynamic UI elements?
Viewport units like vw include scrollbars in most browsers, which can slightly overstate available width. Browser zoom affects effective DPR and selection accordingly. Because sizes is evaluated pre-layout, it cannot respond to container size or late-inserting UI; choose conservative values or clamp with min() to accommodate such variability.
Synonyms
Learn More
Explore OPT-IMG's image optimization tools to enhance your workflow and get better results.