SVG viewBox Explained
The viewBox attribute controls everything about how SVG content maps to its display area. Master it to control cropping, scaling, and responsiveness.
viewBox Syntax
viewBox='min-x min-y width height'. Four numbers separated by spaces or commas. Defines the coordinate space of the SVG content.
- min-x: left edge of the viewport in SVG coordinates
- min-y: top edge of the viewport in SVG coordinates
- width: how wide the viewport is in SVG coordinates
- height: how tall the viewport is in SVG coordinates
- Example: viewBox='0 0 100 100' — content fills a 100×100 coordinate space
viewBox vs width/height Attributes
These two things are different and often confused.
- viewBox: defines the SVG coordinate system (internal)
- width/height on <svg>: defines the display size (external)
- viewBox='0 0 24 24' means path coordinates are in 0-24 range
- width='100px' height='100px' means the SVG renders at 100×100 pixels on screen
- You can set width='200' but keep viewBox='0 0 24 24' — the SVG scales 8× internally
Using viewBox for Cropping and Zooming
Change viewBox values to zoom in or crop the SVG content.
- Original full view: viewBox='0 0 200 200'
- Zoom into top-left quadrant: viewBox='0 0 100 100'
- Pan to the right: viewBox='100 0 100 100'
- Letterbox (show only center strip): viewBox='0 50 200 100'
- This technique creates zoomable SVG maps and diagrams
Making SVG Responsive with viewBox
The key to responsive SVG: use viewBox, remove fixed width/height, control size in CSS.
- In the SVG file: <svg viewBox='0 0 200 100'> — remove width and height
- In CSS: svg { width: 100%; height: auto; }
- The SVG now fills its container width while maintaining the 2:1 aspect ratio
- max-width: 400px prevents it from growing beyond a reasonable display size
Frequently Asked Questions
What happens if viewBox and the SVG display size have different aspect ratios?
preserveAspectRatio controls this. Default is 'xMidYMid meet' — letterboxes the content (adds empty space). Use 'xMidYMid slice' to fill the display area (may crop content).
Can I animate the viewBox attribute?
Yes. Animating the viewBox creates a pan-and-zoom effect. Use GSAP or CSS @keyframes targeting the viewBox attribute for SVG map zoom animations.
Do I always need a viewBox?
Yes, for responsive SVGs. If only width and height are set, the SVG won't scale. viewBox is required for proper responsive behavior.
How do I find the correct viewBox values for an SVG?
Open in Inkscape. File > Document Properties shows the canvas bounds. In Illustrator, the artboard dimensions give you the viewBox values.
Can viewBox coordinates be negative?
Yes. viewBox='-10 -10 120 120' shifts the viewport origin by (-10,-10), showing content that extends 10 units to the left and above the 0,0 origin.
Related guides
Ready to Convert Your Image to SVG?
Free online converter — no sign-up, no watermarks, results in under 3 seconds.
Convert Image to SVG — Free