Course contentsShow
← Web Development
Lesson 2043 of 2,98237. Image and Asset OptimizationFree lesson

SVG viewBox and Sizing

Master viewBox attribute to create scalable icons that maintain proportions at any size without distortion.

SVG viewBox and Sizing

You'll learn how to use the viewBox attribute to create perfectly scalable SVG icons that never distort, no matter the display size.

The Core Problem

When you embed an SVG, you need to control two things: how much of the SVG's "canvas" is visible, and how that canvas scales to fit different container sizes. Without proper configuration, your icons can stretch, crop unexpectedly, or fail to scale at all.

Understanding viewBox

The viewBox attribute defines the coordinate system of your SVG. Think of it like looking through a camera viewfinder: it determines what portion of the SVG world you're capturing and how it maps to the physical display size.

The syntax is: viewBox="min-x min-y width height"

<svg viewBox="0 0 24 24" width="48" height="48">
  <path d="M12 2L2 7v10c0 5.55 3.84 10.74 9 12 5.16-1.26 9-6.45 9-12V7l-10-5z"/>
</svg>

Here, viewBox="0 0 24 24" means "show me the SVG content from coordinates (0,0) spanning 24 units wide and 24 units tall." The width and height attributes control the actual rendered size (48×48 pixels), but the viewBox ensures content scales proportionally.

Why This Matters

Without a viewBox, changing width or height alone won't scale your icon—it just changes the viewport size, potentially clipping content. The viewBox creates the ratio that maintains proportions. You can then set any width/height combination, and the browser scales everything inside perfectly.

Key Takeaway: The viewBox attribute defines your SVG's internal coordinate system and scaling ratio, enabling icons to resize without distortion—set it once, then control display size freely with CSS or attributes.