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

Livereload.js is failing to load due to an invalid address

Snippet from Gruntfile.js: connect: { options: { port: 4000, hostname: 'localhost', livereload: 4002 }, livereload: { options: { open: true, middleware: function (connect) { return [ connect.st ...

I'm receiving the error message "Fatal error: Call to a member function query() on a non-object," what could be causing this issue?

Need help with fixing an error on my private server realmeye. The error message I'm receiving is: Fatal error: Call to a member function query() on a non-object in /home/noxus/public_html/realmeye/index.php on line 112 =========================== ...

What is the method for obtaining the size of a mesh object in pixels (instead of Vector3) within BabylonJS?

Exploring Babylon.js How can I retrieve the size of a mesh object in pixels instead of Vector3 in a React application using Babylonjs? This is what I attempted: let meshPixelSize = meshObject.getBoundingInfo().boundingBox; ...

Global jQuery variables are unexpectedly coming back as "undefined" despite being declared globally

I need to save a value from a JSON object in a global variable for future use in my code. Despite trying to declare the country variable as global, it seems like it doesn't actually work. $.getJSON(reverseGeoRequestURL, function(reverseGeoResult){ ...

How can you limit access to certain routes in Nuxt.js to only clients who possess a valid JWT token?

In Nuxt.js, implementing authentication can be done in the following steps: The client authenticates by sending its credentials in an HTTP request to a specific API route in the Nuxt backend; The Nuxt backend responds with a JWT token for accessing protec ...

What methods can be employed to maintain a consistent width for a multi-line span that aligns with the content?

Inside a div, I have 2 spans. When the content of the first span is short enough to fit on one line, the span's width matches the text content and positions the second span next to it. If the content of the first span is long and causes it to wrap, t ...

What are the advantages of implementing HTML5 canvas for animation?

I'm a beginner in html5 and I've recently been experimenting with the canvas element. Can anyone provide insight on when the canvas would be most beneficial or practical to use? Essentially, what are some scenarios where it is recommended to util ...

developing an associative object/map in JavaScript

I have a form featuring various groups of checkboxes and I am attempting to gather all the selected values into an array, then pass that data into an Ajax request. $('#accessoriesOptions input').each(function(index, value){ if($(this).prop(& ...

Is there a way to enable autofill functionality if an email already exists in the database or API within Angular 12?

In order to auto-fill all required input fields if the email already exists in the database, I am looking for a way to implement this feature using API in Angular. Any guidance or suggestions on how to achieve this would be greatly appreciated. ...

What is the mechanism behind jQuery triggering the execution of JavaScript code contained in script tags that are retrieved in an AJAX response?

What is the unique ability of jQuery that allows JavaScript code inside script tags in an AJAX response to be executed? In the absence of jQuery AJAX, using eval() has been a common method to achieve this functionality as discussed in posts such as: Cal ...

methods for transforming JSON array output objects into individual non-array values

I'm facing an issue with a JSON result that contains latitude and longitude as an array like [13.0801721, 80.2838331]. I need help in converting this to comma-separated values without the array brackets, similar to 13.0801721, 80.2838331. This is my ...

Opting for CSS3 transitions over jQuery animate

Currently, I am working on animating a block of HTML that involves fading in (opacity) and slightly moving from the left (margin-left)... $('.latest-stats').delay(1000).animate({ opacity: 1, marginLeft: '55px' }, 1000, function () { ...

Is Typescript capable of converting ES6 code to ES5 during transpilation?

Currently, I'm in the process of developing an application utilizing Angular 2 and TypeScript. My goal is to incorporate a JavaScript method, specifically 'filter' for arrays, that is compatible with IE 11+, Chrome 45+, and other similar bro ...

Should servlet response be HTML for use in AJAX calls?

I am currently in the process of developing a web application with multiple pages, including index.html which serves as the main page and contains various <a> tabs linking to different Servlet pages. As part of my design, I have a consistent CSS lay ...

I am encountering an issue with my register button not being able to submit in PHP+AJAX, while the

Having trouble with the registration page in PHP and AJAX. The login section works fine as I can sign in, but the registration button appears disabled or inactive, preventing form submission. I suspect an error somewhere, but unable to pinpoint it. Login ...

Layering digital sheets of paper and rearranging them with the help of CSS

I want to create a visual representation of a stack of paper sheets as a metaphor. The idea is to neatly stack the sheets on top of each other, with only the header of each sheet visible and the rest of the content covered. !-------------- | Sheet 1 +--- ...

Every time I switch tabs in Material UI, React rebuilds my component

I integrated a Material UI Tabs component into my application, following a similar approach to the one showcased in their Simple Tabs demo. However, I have noticed that the components within each tab — specifically those defined in the render method ...

What is the best method to locate an element<T> within an Array[T] when <T> is an enum?

I've recently started learning TypeScript and exploring its functionalities. I could use some assistance in deepening my understanding. Within our angular2 application, we have defined an enum for privileges as follows: export enum UserPrivileges{ ...

What is the most efficient way to calculate the sum of all the numbers lying between the endpoints

I am faced with a complex array The array looks like this: let arr = [[2, "OR", 22, 22, "OR", 22, 20], [300, "OR", 22, 300, "OR", 22, 22, "OR", 1], [1212, 2, "OR", 1]] My goal is to extract and ...

Turn off browser feature that automatically adds overflow:hidden on touch screen devices

Encountering a problem with browsers (potentially Chrome) adding CSS rules on touch-enabled devices. In a website developed for a client (specifically for Chrome), the scroll bars disappear on elements when accessed from their ultrabooks. The client still ...