Height attribute

HTML

In HTML, the height attribute on an img element is a presentational attribute that sets the intended display height in CSS pixels using an integer value without units. When provided alongside a width attribute, it conveys an aspect ratio so the browser can reserve correct layout space before the image data is decoded and painted, reducing layout shifts. Modern user agents treat width and height attributes as hints that map to the corresponding CSS properties and influence the computed aspect-ratio. CSS rules still take precedence at render time, but the attributes inform early layout and improve stability.

How height relates to width

The height attribute defines one side of the rendered image box in CSS pixels but, on its own, does not establish the element’s aspect ratio. If only height is present, the browser cannot infer the corresponding width until it knows the image’s intrinsic dimensions, which may require downloading headers or decoding. This uncertainty can postpone stable layout and may cause late reflow when the actual dimensions become available.

When height and width are both present, the browser derives an aspect ratio (width ÷ height) and can reserve the correct slot before the image loads. This pre-allocation prevents elements below the image from shifting as the image paints. The attribute pair also maps to CSS width and height as presentational hints, guiding the used size if no overriding CSS is applied.

If the width and height attributes do not reflect the image’s intrinsic ratio, the browser still treats them as the intended box size. By default, the image content is then stretched to fill that box (object-fit: fill), which can distort the image. Authors commonly pair correct width and height attributes with CSS that allows responsive scaling (for example, width: 100%; height: auto) to preserve aspect ratio at different viewport sizes.

Responsive image sets should keep a consistent aspect ratio across candidates in srcset to ensure the ratio derived from width and height remains valid regardless of which resource the browser selects. Mixing aspect ratios among candidates can undermine the pre-calculated layout and cause layout shifts when the selected image’s intrinsic ratio differs.

Definition and metric: Cumulative Layout Shift (CLS) quantifies unexpected visual movement during a page’s lifecycle. Each layout shift score equals impact fraction × distance fraction, and CLS is the sum of these scores. Core Web Vitals classifies CLS at the 75th percentile of page loads: Good ≤ 0.1, Needs improvement > 0.1–0.25, Poor > 0.25 (measured separately on mobile and desktop).

Images without reserved space are a common cause of layout shifts. When an image loads and pushes content down, the resulting movement contributes to the CLS score. Explicit width and height attributes let the browser compute an aspect-ratio box and allocate space before the image is decoded, reducing unexpected movement and improving CLS reliability across fluctuating network and device conditions.

CLS is computed by summing individual shift scores, where each score is the product of the impact fraction (how much of the viewport moved) and the distance fraction (how far it moved). Even small shifts can add up, especially on long sessions. Images are frequent contributors because they often sit above text or calls to action. Reserving space via height and width attributes is a low-cost way to constrain shifts at scale.

Core Web Vitals evaluates CLS at the 75th percentile of page loads for both mobile and desktop. A page is considered good if CLS is ≤ 0.1, needs improvement between 0.1 and 0.25, and poor above 0.25. Adding height and width to images is one of the most reliable mitigations that does not trade off against other metrics; it improves stability without increasing transfer size or blocking rendering.

Purpose in HTML layout

The height attribute exists to communicate the intended display dimension of the image in the document’s layout. It helps the browser construct a stable layout tree during initial parsing, before image data arrives. Because img is a replaced element, its intrinsic size is not known until the resource is consulted; declarative dimensions provide an early signal to avoid speculative layout that must be corrected later.

Beyond reserving space, height and width act as presentational defaults. In the absence of overriding CSS, they define the used size. When both attributes are present, they implicitly define an aspect ratio that CSS layout can use even when the image is not yet decoded. This behaviour supports responsive designs where CSS scales the element while maintaining a consistent ratio across breakpoints.

Providing explicit dimensions is also a form of resilience. If the image fails to load, the reserved box maintains the document flow and prevents text from collapsing into unexpected positions. That predictability aids perceived quality and reduces cumulative jank during image retries, slow connections, or when placeholders and low-quality previews are used as interim content.

CSS overrides and browser behavior

HTML width and height are presentational hints that map to CSS width and height. The CSS cascade and the box model determine the final used size. If CSS specifies a different height, that value overrides the attribute. When one dimension is auto in CSS, the browser can use the element’s aspect ratio (from attributes or intrinsic data) to compute the other dimension, which preserves proportional scaling by default.

Modern browsers compute an aspect ratio for img from any numeric width and height attributes, even if CSS later scales the element. This allows early layout with a ratio-correct placeholder. If the attributes conflict with CSS constraints such as max-height or min-height, standard sizing rules resolve the final box; the aspect ratio continues to guide calculation unless both width and height are explicitly fixed by CSS, which can distort content under object-fit: fill.

Lazy-loading, decoding, and resource selection occur after layout is established. The presence of height and width attributes does not delay image loading and does not increase transfer size. Instead, it enables the browser to render surrounding content immediately with stable spacing. If responsive images are used, the selected candidate replaces the placeholder while retaining the same layout box, preserving stability when aspect ratios match.

Role in layout and rendering: The HTML height (and width) attributes communicate an image’s intrinsic pixel dimensions to the browser. Modern browsers use these attributes to compute the element’s aspect ratio and reserve the correct layout space before the image data downloads. This reduces unexpected reflows when the image loads.

During the style and layout phases, browsers build a render tree and assign box sizes. For images, early sizing is uncertain without declared dimensions. The height attribute, combined with width, supplies enough information to calculate a ratio and a provisional box, allowing text and other elements to layout around the image without waiting for network or decode stages. This is especially valuable above the fold where movement is most noticeable.

When the image resource becomes available, the browser reconciles the intrinsic dimensions with the computed box. If the attributes match the intrinsic ratio, no re-layout is needed; the decoded image paints into the allocated slot. If they differ, a correction or stretching occurs depending on CSS rules. Aligning attributes to the true intrinsic size is the most stable strategy across devices and densities because they are interpreted in CSS pixels, not device pixels.

In responsive layouts, CSS typically scales the box, but the ratio derived from the attributes remains in effect. This means a 1200×680 image can be declared with height="680" and width="1200" and be displayed at, for example, 600×340 or 300×170 without distortion. The reserved space adapts with the container while maintaining proportionality, ensuring stable, predictable rendering across breakpoints and orientations.

Implementation notes

Set width and height attributes to the image’s intrinsic pixel dimensions. This allows the browser to infer a reliable aspect ratio. Even if CSS resizes the element, the ratio helps reserve space and avoid layout shifts. Values are unitless integers interpreted as CSS pixels; do not include "px" or other units. For high-density displays, continue to use intrinsic pixel values; device pixel ratio is handled via srcset and sizes, not by altering these attributes.

Ensure all responsive image candidates share the same aspect ratio. If variants differ, the precomputed ratio may be wrong for the selected resource, leading to reflow or letterboxing depending on object-fit. For art-directed images that change ratio across breakpoints, consider scoping different width and height values in separate markup branches or containers that swap via media queries to preserve stability per layout context.

Practical checklist

  • Provide both width and height attributes on img; avoid using only one.
  • Match attributes to the image’s intrinsic dimensions so the inferred ratio is accurate.
  • Use CSS to scale responsively (e.g., width: 100%; height: auto) rather than altering attributes.
  • Keep aspect ratios consistent across srcset candidates to prevent CLS.
  • Prefer attributes or CSS aspect-ratio over spacer elements for reserving layout space.

Comparisons

Height attribute vs CSS height property

The height attribute is parsed early and can inform pre-layout sizing; CSS height is resolved after the cascade. CSS wins in conflicts and is more flexible with units, calc(), and min/max constraints. For stability, the attribute helps reserve space; for design control, CSS governs the final size. In practice, use both: attributes for ratio and initial slot, CSS for responsive scaling and constraints.

Height/width attributes vs CSS aspect-ratio property

CSS aspect-ratio can reserve space without knowing intrinsic dimensions and works for any element, not just img. However, it does not convey the intrinsic pixel size and requires author-supplied values in CSS. Width and height attributes both reserve space and align with the image’s real ratio when set to intrinsic numbers. Many teams combine them: attributes for intrinsic ratio and CSS aspect-ratio for non-image placeholders or art-directed containers.

Height attribute vs placeholder techniques (spacers, skeletons)

Spacer divs and skeletons can reserve space but add extra markup and can drift if ratios change. The height and width attributes are lightweight, standardised, and travel with the image element, reducing maintenance. Placeholders remain useful for perceived performance, but they should honour the same aspect ratio derived from attributes to avoid shifts when the real image loads.

FAQs

Should the height attribute match the image’s intrinsic pixel height?

Yes. Set height and width to the intrinsic pixel dimensions of the source image. This ensures the browser computes the correct aspect ratio and reserves accurate space. Responsive scaling should be handled in CSS. Do not use CSS-scaled values or include units; the attributes are unitless integers interpreted as CSS pixels, independent of device pixel ratio.

What happens if only height is specified without width?

The browser sets the image’s used height to that value, but cannot reserve a proportional width until it knows the intrinsic dimensions or an aspect ratio from elsewhere. This can lead to unstable layout. Providing both height and width, or using CSS aspect-ratio, allows the browser to calculate both dimensions up front and avoid reflow when the image loads.

Do height and width attributes affect SEO directly?

They do not change indexing or ranking signals directly, but they influence Core Web Vitals, particularly CLS, which is a page experience signal. More stable pages tend to perform better in user metrics and can indirectly benefit search performance. Explicit dimensions also reduce layout jank for users, which can improve engagement and conversion outcomes.

How do height and width interact with srcset and sizes?

The attributes provide a ratio for layout, while srcset and sizes guide resource selection based on viewport and density. The chosen candidate is then fit into the pre-reserved box. Ensure all candidates share the same aspect ratio as implied by the attributes; otherwise, the browser may need to adjust the layout or scale the content in ways that introduce shifts or cropping depending on object-fit.

Is the height attribute needed if CSS aspect-ratio is used?

CSS aspect-ratio can reserve space, so strictly speaking the attribute is not required. However, using height and width on img remains beneficial because it couples the ratio to the intrinsic image data, is understood by user agents during HTML parse, and is backwards-compatible. Many production sites combine both patterns: attributes for images, CSS aspect-ratio for non-image containers and placeholders.

Synonyms

img height attributeHTML img heightimage height attributeheight attribute (HTML)height on img