SVGSVGElement: viewBox property
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
TheviewBox read-only property of theSVGSVGElement interface reflects the<svg> element'sviewBox attribute as anSVGAnimatedRect.
The property describes the<svg> element'sviewBox attribute, which is used to defined the x-coordinate, y-coordinate, width, and height of an<svg> element. TheSVGAnimatedRect.baseVal andSVGAnimatedRect.animVal properties are bothSVGRect objects, ornull if theviewBox is not defined. These objects' components may differ from theSVGSVGElement.x,SVGSVGElement.y,SVGSVGElement.width andSVGSVGElement.height properties, as thex,y,width, andheight attributes take precedence over theviewBox attribute.
For non-nested SVG elements, the values of the CSSx,y,width, andheight properties take precedence over any element attributes, so the values defined by theviewBox may not be reflected in the element's appearance.
In this article
Value
Example
Give the following SVG opening tag:
<svg viewBox="-12 -18 200 300" x="5" y="5" height="400" width="600"></svg>We can retrieve theviewBox values, but they differ from thex,y,width, andheight properties:
const svg = document.querySelector("svg");const vBox = svg.viewBox;// The SVGSVGElement viewBox propertyconsole.dir(vBox); // SVGAnimatedRect { baseVal: SVGRect, animVal: SVGRect }console.log(vBox.baseVal.x); // -12console.log(vBox.baseVal.y); // -18console.log(vBox.baseVal.width); // 200console.log(vBox.baseVal.height); // 300// Other SVGSVGElement propertiesconsole.log(svg.x); // 5console.log(svg.y); // 5console.log(svg.width); // 400console.log(svg.height); // 600Specifications
| Specification |
|---|
| Scalable Vector Graphics (SVG) 2> # __svg__SVGFitToViewBox__viewBox> |