The Angular Material documentation app features an SVG Viewer that is able to scale the SVG content to fit the container using the following function:
inlineSvgContent(template) {
this.elementRef.nativeElement.innerHTML = template;
if (this.scaleToContainer) {
let svg = this.elementRef.nativeElement.querySelector('svg');
svg.setAttribute('width', '100%');
svg.setAttribute('height', '100%');
svg.setAttribute('preserveAspectRatio', 'xMidYMid meet');
}
}
It seems that all we need to do to achieve responsive scaling of the SVG is to ensure it is saved with the correct viewBox
parameters, as explained in this Stack Overflow post.
For example, the demo circle provided in the answer looks like this:
<svg viewBox="0 0 100 100">
<circle cx="50" cy="50" r="40" fill="gold"/>
<rect x="10" y="50" width="20" height="50" fill="gold"/>
<rect x="70" y="50" width="20" height="50" fill="gold"/>
<circle cx="35" cy="45" r="5"/>
<circle cx="65" cy="45" r="5"/>
</svg>
This circle will automatically adjust to fit any container without needing to set width=100%
and height=100%
. This leads me to wonder if the Angular team sets specific width and height for other use cases.
I am intrigued by this design choice and interested in understanding if there are additional benefits to this approach. Is this a common pattern among UX developers, and if so, what are the reasons behind it?