The SVG viewBox attribute establishes the drawing coordinate system and the area made visible inside an SVG. Its four space-separated numbers are origin x, origin y, width, and height. For example, `viewBox="0 0 900 300"` starts the coordinate system at `(0,0)` and uses a 900-by-300 drawing area. section 1.2.2
Use `viewBox` to make an SVG responsive without stretching its design. Remove fixed `width` and `height` attributes, then give the SVG a viewBox matching the dimensions used to position its shapes. As the available container changes size, the SVG scales while retaining the aspect ratio defined by the final width and height values. section 1.2.2
Read the four values in order:
- `min-x` — the horizontal origin of the viewBox coordinate system. section 1.2.2
- `min-y` — the vertical origin of the viewBox coordinate system. section 1.2.2
- `width` — the coordinate-system width, which contributes to the SVG aspect ratio. section 1.2.2
- `height` — the coordinate-system height, which completes the SVG aspect ratio. section 1.2.2
Changing the first two values can change which portion of the SVG container is visible. A `0 0` origin is a practical default for placing shapes with familiar coordinates such as `x`, `y`, `cx`, and `cy`; shifting that origin instead changes the visible region. section 1.2.2
The viewBox controls the SVG’s internal drawing space, while the parent container can limit its rendered size. Wrap the SVG in a container with `width:100%`, a maximum width, and centered margins when a graphic should fill available space but not outgrow surrounding page content. section 1.2.2
Create a responsive SVG with D3
Append an SVG to a responsive container, then set `viewBox` with D3’s `.attr()` method. Attribute names are case sensitive: write `viewBox` with a capital `B`. Here, `1200` matches the container’s maximum width and `1600` defines the planned drawing height. `const svg = d3.select(".responsive-svg-container")` ` .append("svg")` ` .attr("viewBox", "0 0 1200 1600");` The resulting SVG adapts when the browser viewport becomes smaller while preserving a 1200:1600 aspect ratio. section 2.5
d3.select(".responsive-svg-container")
.append("svg")
.attr("viewBox", "0 0 1200 1600");
Inspect a compact D3 example that appends an SVG and assigns its responsive `viewBox` value. section 2.5
Choose viewBox dimensions before laying out a chart. Shape positions and sizes are expressed in that coordinate system, so a rectangle at `x="10"` and `y="10"` is positioned relative to the viewBox rather than to a fixed screen-pixel SVG size. The dimensions can be adjusted later as the graphic grows. section 1.2.2 section 2.5

