Is there any benefit to making the SVG elements width and height 100%?

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?

Answer №1

Consider this situation where it may be beneficial, as the method in question appears to be unaware of how the svg element was declared. Therefore, by overriding these attributes, any previous settings won't hinder the responsiveness of the element.

Given its name inlineSvgContent, it can be inferred that this function serves as a type of sanitizer.

It is common practice (and often recommended) for standalone svg images to have absolute width and height attributes specified in pixels, ensuring the renderer can accurately display them. In cases where this isn't done, the default rendering would be at 100%, which could lead to uncertain outcomes. Defining absolute width and height establishes a consistent aspect ratio.


However, if you were to create the element from scratch, setting these attributes would be redundant since they are actually the default values:

const svg = document.createElementNS( 'http://www.w3.org/2000/svg', 'svg' );

console.log( 'width', svg.width.baseVal.valueAsString ); // 100%
console.log( 'height', svg.height.baseVal.valueAsString ); // 100%
console.log( 'preserveAspectRatio', svg.preserveAspectRatio.baseVal );
// align: 6 => SVG_PRESERVEASPECTRATIO_XMIDYMID
// meetOrSlice: 1 => SVG_MEETORSLICE_MEET
// => "xMidYMid meet"

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Connect two radio buttons across separate forms

I am encountering an issue with two radio buttons that I am trying to link together. The problem arises because they are located in two separate form elements, causing them not to function as intended. It is important for the forms to be utilized in Bootst ...

Tips for creating a new terminal window and interacting with it?

I have a node server that generates logs of activities in the terminal. To have more control over the server during runtime, I aim to integrate a repl server within it. However, I need to ensure that the logs and repl server do not interfere with each ot ...

Angular ngx-translate not displaying image

My Angular application is utilizing ngx-translate to support multiple languages. I am trying to dynamically change an image based on the language selected by the user. However, I am facing difficulty in updating the image when a language is clicked. The ap ...

Execute the Selenium function repeatedly using values from an array in a loop

I am facing a challenge with running a selenium script in a loop to populate a database. I have an array of objects consisting of 57 items that need to be processed through the loop asynchronously. My goal is to iterate through each store, check its status ...

Styling a HTML div element with a header and footer, while also ensuring that the

My goal is to create a div that features a header with a unique background design. The content within the div should have a background consisting of a one-pixel repetition at y, or maybe something different? I also want a footer with its own distinctive ...

How come an element retrieved with getElementById in Next.js comes back as null despite the presence of a defined document?

Having trouble using SSR in my React/Next app. Despite having the document present (and being able to visually see the div with the id plTable), the getElementById function is returning null. I even tried calling getElementById after 6 seconds to ensure ...

What is the correct way to extract a value from a keyvalue pair?

When dealing with an object that returns boolean "issues", I specify it as a string. If the value is true, I aim to show a checkmark; if false, I want to display a cross. <ul *ngFor="let filtered of reposFiltered | keyvalue"> <li *ngIf=& ...

Is your Angular 2 routing failing to work properly after a page refresh or reload when using gulp?

I've recently started learning Angular 2, and I encountered an issue with routing. During the development phase, I ran my application using npm start. However, after migrating to gulp.js, when I run the application by typing gulp, everything works fin ...

Sort by user identifier

I'm having an issue trying to filter a list of posts and comments by userId. I've passed the userId params as postCreator and commentCreator, but something seems to be amiss. Can anyone help me identify what I might be doing wrong? // Defining ...

Enhance your spreadsheet by incorporating dynamic columns utilizing xlsx and sheetjs libraries

I have an array consisting of multiple tags with unique ids and corresponding data: [ { "id": "tagID1", "error": { "code": 0, "success": true }, "data": [ [1604395417575, 108 ...

Leverage the power of personalized SCSS styles in combination with Bootstrap-Vue, Webpack, and

I have been working on an application using VueJS with Bootstrap-Vue and I encountered a challenge while trying to import a SCSS file to customize the Bootstrap variables and add some custom styles. Here are the steps I have taken so far: Installed node ...

What is the method for executing PHP code without the need for users to access the webpage?

Similar Query: Optimal method for running a PHP script on a schedule? I am in need of a solution where a PHP script can consistently fetch data from a single website, store it in a database on the server, and then update multiple other websites. The c ...

Transforming CSS Styles of Elements with Bootstrap

After incorporating links and scripts for Bootstrap v4.5 into my project, I quickly noticed that it automatically overrides the styles of text, buttons, and other elements I had previously customized. While I added a Bootstrap alert for authentication pur ...

Activate outline styling for Bootstrap radio buttons when clicked

I was in the midst of developing my bootstrap application. Every time I click on a radio button, there is a noticeable blue outline as shown here: https://i.sstatic.net/Uzm7b.png I attempted to address this issue using the following CSS code: .form-chec ...

Utilizing ellipses within a list item to create a visually appealing design

I've been struggling with this problem for hours, but I can't seem to find a solution. How can I ensure that the text in a list item respects the size of its parent container and uses an ellipsis when necessary? Here's the scenario: <?P ...

How to temporarily change CSS color for 5 seconds using JavaScript and incorporate an easing effect?

Regarding this query: JavaScript - Modifying CSS color for 5 seconds Here is a live example of the solution: http://jsfiddle.net/maniator/dG2ks/ I am interested in adding an easing effect to the transition, gradually making the color fully opaque and t ...

Exploring the possibilities with JavaScript options

I am currently working on a project that involves a dropdown list... to complete unfinished sentences. Unfortunately, I am facing an issue with a message stating Uncaught TypeError: Cannot read property 'options' of null Below is a portion of m ...

Unable to execute any actions on object in JavaScript

I currently have two functions in my code: getRawData() and getBTRawData(). The purpose of getBTRawData() function is to retrieve data from Bluetooth connected to a mobile device. On the other hand, getRawData() function takes the return value from getB ...

showing a pop-up message when a specific javascript function is triggered

Here is a unique code snippet showcasing a customized dialog box created with HTML, CSS, and JavaScript. The dialog box is displayed when a button is clicked. <!DOCTYPE html> <html> <head> <style> /* Custom Modal Styles */ .modal { ...

Dynamically setting properties in a Vue component using Angular

After browsing through this interesting discussion, I decided to create a web component: <my-vue-web-comp [userId]="1"></my-vue-web-comp> Initially, everything was working smoothly in Angular when I assigned a static property. Howeve ...