Blog>
Snippets

Angular SVG ViewBox for Responsive Design

Show how to utilize SVG's viewBox attribute to create scalable vector graphics that maintain their aspect ratio and adapt to different screen sizes in an Angular application.
import { Component } from '@angular/core';

@Component({
  selector: 'app-svg-component',
  template: `
    <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 200 200" preserveAspectRatio="xMinYMin meet">
      <!-- Define your graphic elements here -->
      <circle cx="100" cy="100" r="80" fill="green" />
    </svg>
  `
})
export class SvgComponent {
  // Add any necessary component logic here
}
This Angular component, SvgComponent, renders an SVG element with a viewBox attribute set to '0 0 200 200', which defines the coordinate system of the SVG. The preserveAspectRatio attribute with the value 'xMinYMin meet' ensures that the aspect ratio is maintained while scaling to fit the container. The SVG is set to occupy 100% of the width and height of its container, making it responsive. Inside the SVG, a green circle is defined for demonstration purposes.
@Component({
  selector: 'app-responsive-svg',
  template: `
    <div style="width: 100%; height: 100%; max-width: 400px; margin: auto;">
      <app-svg-component></app-svg-component>
    </div>
  `,
  styleUrls: ['./responsive-svg.component.css']
})
export class ResponsiveSvgComponent {
  // This component wraps the SvgComponent to put it in a responsive container
}
The ResponsiveSvgComponent creates a responsive container for the SvgComponent, styling it to take up 100% of the width and height, with a maximum width of 400px. The container is centered using auto margins. This structure allows the SVG to adapt to different screen sizes while maintaining its aspect ratio.