Rescale SVG to a Target size

Summary

Rescaling SVG artwork to fixed dimensions (e.g., 64×64) requires explicit width and height attributes in the root <svg> element. When missing, browsers render the SVG at its internal “viewBox” size (1000×1000 here), ignoring the target display dimensions. Adding width="64" height="64" solves the issue.

Root Cause

The SVG lacked explicit dimensions. Its scaling behavior relies on two attributes:

  • viewBox: Defines internal coordinate space and aspect ratio (e.g., 0 0 1000 1000).
  • width/height: Dictate rendered output dimensions (missing here).
    Without width/height, the idols render at absolute viewBox sizes, leading to oversized shapes.

Why This Happens in Real Systems

  1. Artifacts exported from design tools default to source viewBox dimensions.
  2. Dynamic asset reuse: SVGs authored for print/web might lack explicit sizing for new contexts.
  3. Assumption that viewBox controls rendering size.

Real-World Impact

  • Improperly sized UI elements (e.g., icons rendering at 1000px instead of 64px).
    -彰显Layout shift when unconstrained SVGs overlap content.
  • Performance degradation if oversized SVGs consume excessive memory.

Example or Code


  

How Senior Engineers Fix It

  1. Explicitly define width and height matching target render size.
  2. Preserve viewBox to maintain internal coordinates/aspect ratio.
  3. Use CSS for dynamic scaling:
    svg {
      width: 64px;
      height: 64px;
    }
  4. For non-square targets, leverage preserveAspectRatio (e.g., xMidYMid slice).

Why Juniors Miss It

  • Misunderstanding viewBox as a sizing directive instead of a coordinate system.
  • Over-reliance on design tool outputs without inspecting SVG markup.
  • Belief that scaling requires manual coordinate adjustments.
  • Confusion between image dimensions (<img> attributes) and SVG intrinsic sizing.