Published on

The `viewBox` attribute in SVG files

Authors
  • avatar
    Name
    hwahyeon
    Twitter

The viewBox attribute in an SVG file defines the coordinates and dimensions of the content, determining how a specific area is displayed. This allows SVG graphics to scale appropriately across screens of various sizes.

Structure of the viewBox Attribute

viewBox="min-x min-y width height"
  • min-x: Starting x-coordinate of the view box
  • min-y: Starting y-coordinate of the view box
  • width: Width of the view box
  • height: Height of the view box

How It Works

The viewBox defines the relationship between the SVG's internal coordinate system and the viewport in which it is rendered.

  1. Setting the Internal Coordinate System
    The viewBox sets up the internal coordinate system, which determines how SVG elements are positioned.

  2. Scaling to Match the Viewport
    The browser scales the SVG elements to fit the screen based on the viewBox values.

Example

<svg width="200" height="200" viewBox="0 0 100 100">
  <circle cx="50" cy="50" r="40" fill="blue" />
</svg>
  • viewBox="0 0 100 100": Defines the internal coordinate system starting at (0, 0) with a width and height of 100.
  • The SVG renders at 200×200 pixels, scaling the internal coordinate system accordingly, making the elements appear larger.