when using the svg element in the browser, it is recommended to specify a width and…
- User
when using the svg element in the browser, it is recommended to specify a width and height in pixels. Aren't absolute pixel values now frowned upon?
- Assistant
Short answer
“Pixels are bad” is an over-simplification. For SVGs the native width/height attributes are still the most reliable way to:• reserve the right amount of space up-front (eliminates CLS/layout-shift)
• give the browser something concrete to start with before CSS kicks in
• let the viewBox scale cleanly at any other size you decide laterSo, adding width="200" height="80" is not a 2010-era mistake; it’s usually the best default.
─────────────────────────────────────────────
Why it isn’t the same as hard-coding pixel fonts, etc.
─────────────────────────────────────────────-
Attribute ≠ CSS declaration
• width="200" on the element is a presentational hint that can be overridden by CSS.
• If later you do .logo { width: 10rem; height: auto; } CSS wins. -
“px” inside the attribute is unitless by spec
• The SVG 2 spec says numbers are interpreted in CSS px units, but you never actually write the “px”.
• They therefore scale together with the page’s device-pixel-ratio rules (1 CSS px ≠ 1 hardware px on Hi-DPI screens), so they’re already “responsive” in the modern sense. -
Preventing cumulative layout shift (CLS)
• Lighthouse and Web Vitals penalize you when images/SVGs don’t have dimensions and the browser has to guess.
• Setting width/height lets the browser allocate the box immediately, making your page feel snappier.
─────────────────────────────────────────────
Typical modern pattern
─────────────────────────────────────────────<svg width="128" <!-- space is reserved --> height="128" viewBox="0 0 128 128" role="img" aria-labelledby="title" class="icon"> <!-- CSS can still override --> … </svg>CSS layer (optional):
.icon { /* scales according to context */ width: 2.5rem; height: auto; /* preserves aspect ratio from width/height attribute */ }If you truly want it to be fluid without an initial fixed box, drop the width/height attributes and rely solely on CSS; just accept the CLS cost or use a placeholder aspect-ratio box:
.svg-fluid { inline-size: 100%; aspect-ratio: 1 / 1; /* reserves space */ }─────────────────────────────────────────────
Rule of thumb
• Inline SVG in markup you control? Give it width/height.
• Icon font replacement or background decoration that already sits inside a flex/grid layout? Use CSS.Pixels are “frowned upon” primarily for text sizing and layout rigidness, not for reserving intrinsic dimensions for graphics that are inherently scalable.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.