Unexpected changes are observed in the size of DIV elements when adjusting the SVG viewBox

My aim is to make the <svg> element have the same dimensions for the viewBox as the <div> it is inside. This means that the viewBox values need to match the dimensions of the containing <div>. Here is an example:

<div style="width:100%; height:100%">
  <svg viewBox="0 0 ?? ??"></svg>
</div>

The containing div should fill its available space on the layout. I am currently using flex:1 in a flexbox, which leads to the same behavior.

To achieve this, I am dynamically setting the viewBox to the dimensions of the containing div. For instance:

svg.setAttribute('viewBox', `0 0 ${div.clientWidth} ${div.clientHeight}`);

However, there is a problem - setting the viewBox actually changes the dimensions of the container div (say what?). This results in the viewBox growing every time the container div changes dimensions due to an event like a window resize. Here is a demonstration:

const setViewBoxToDivDimensions = () => {
  let svg = document.getElementById('mySvg');
  // Set the viewBox of the SVG to the dimensions of the container div
  svg.setAttribute('viewBox', `0 0 ${container.clientWidth} ${container.clientHeight}`);
  // Show the resulting values
  getAndDisplayVals();
}

const getAndDisplayVals = () => {
  let container = document.getElementById('container');
  let svg = document.getElementById('mySvg');  
  
  let dimsResult = `Dimensions of container DIV are: ${container.clientWidth} x ${container.clientHeight}`;
  let vbResult = `viewBox of SVG is: ${svg.getAttribute('viewBox')}`;  
  document.getElementById('dimsResult').innerHTML = dimsResult;
  document.getElementById('vbResult').innerHTML = vbResult;
}

document.getElementById('setViewBox').addEventListener('click', e => {
  setViewBoxToDivDimensions();
});

window.addEventListener('resize', e => {
  setViewBoxToDivDimensions();
  getAndDisplayVals();
});

getAndDisplayVals();
Clicking the button, or resizing the window, will update the viewBox with the dimensions of the "container" DIV. This will actually cause the DIV to grow :/
<p/>
<button id="setViewBox">Change viewBox</button>
<p/>
<div id="vbResult"></div>
<div id="dimsResult"></div>
<div id="container" style="padding:0px; margin:0px">
  <svg id="mySvg" viewBox="0 0 100 100" style="background-color:grey;padding:0px; margin:0px"></svg>
</div>

Answer №1

By adding the display: block css attribute to the SVG element, the issue that was occurring has been resolved.

This change is necessary because without this attribute, the container's height would be slightly higher than the SVG element's height. This is due to the default display: inline property for SVG elements. For more information on why this display property affects the height, check out this resource.

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

"Returning undefined: The outcome of using jQuery's .html() method on

I am having an issue with the JavaScript function I have created to load content from another URL into the current document. For some reason, both contentHtml and menuHtml variables are showing as undefined. Can someone please help me identify where I we ...

Is there a way to retrieve YouTube URLs through programming automation?

I'm currently working on a project to automatically retrieve YouTube URLs and incorporate a download button feature. I found a tutorial suggesting the use of 'ytplayer.config.args.url_encoded_fmt_stream.map.split(",");' After attempting to ...

`WebAuthn API allows for easy identification of fingerprints``

Google introduced WebAuthn https://developers.google.com/web/updates/2018/05/webauthn two years back. Is it possible to accurately identify the finger that a user registered or verified? For instance, the server could not only obtain the public key but a ...

Minimize the cyclomatic complexity of a TypeScript function

I have a typescript function that needs to be refactored to reduce the cyclometric complexity. I am considering implementing an inverted if statement as a solution, but it doesn't seem to make much of a difference. updateSort(s: Sort) { if (s.ac ...

Utilize the assigned value of a variable from a separate file

Is it possible to set a variable in an external file called "Variable.js", assign it a value in a file named "Page1.html", and then use that variable with its assigned value in another file named "Page2.html"? For example, let's consider the contents ...

Preventing React setState from replacing the entire object

When attempting to update a customer's age using setState, the object is altered before calling setState, but the existing object is not updated. customerOnChange(event, field) { //Customer's age currently set at 80 var customer = { ...t ...

What is the best way to update the text on buttons once they've been clicked for a variety of buttons

I'm encountering an issue with multiple buttons where clicking on any button causes the text to change on the first button, rather than the one I actually clicked on. All buttons have the same id, and using different ids for each button seems impracti ...

Automatically switch tabs upon pressing/scanning the Return key (using PHP, MySQL, and JavaScript)

Seeking assistance to resolve an ongoing issue that has been troubling me for the past few weeks. I am maintaining a basic web-based database to keep track of product serial numbers leaving our warehouse. The system is secure behind our firewall, so I&apo ...

What is the best way to create a list using only distinct elements from an array?

If I have a collection of different colors: Red Blue Blue Green I aim to extract only the unique colors and store them in an array. Subsequently, I plan to incorporate each color from that array into an existing color list. The desired outcome would l ...

Steps to configuring reverse gradient in a solitary line

I have successfully resolved similar issues with diagonal gradients in the past. However, I am currently facing challenges with linear gradients. Previously, I was able to create a gradient with a cross pattern. background: linear-gradient(to right, tran ...

Step-by-step guide on displaying a tag image in HTML using html2canvas

html2canvas($('#header'), { allowTaint: true, onrendered: function (canvas) { var imgData = canvas.toDataURL("image/png"); console.log(imgData); } }); click here for an example ...

How to properly structure a Vue file in vscode to meet eslint guidelines

Essentially, what I am seeking is uniformity in: the way vscode formats my .vue file how the eslint checker scans my .vue file when I execute npm run .... to launch the server or build the target Currently, after formatting my document in vscode and then ...

Surrounding a parent div with an additional div element

I'm struggling to summarize my predicament, but let me share some simplified code that highlights the issue (index.html): <html> <body> <div id="wrapper" class="divide"> <div id="top" class="divide"> ...

Updating a table cell triggers a change in every cell

I have a table with columns and I need to calculate values in other cells when there is a change event on the table. I want to use ng-change so that the changes are seen immediately. However, I am unsure of how to properly utilize ng-model - if it is used ...

Guide for creating a function that accepts an array containing multiple arrays as input

I am working with a function called drawSnake and it is being invoked in the following manner: drawSnake( [ [0, 0], [0, 1], [0, 2], [0, 3], [0, 4], ] ); How should I format the input for this function? I have attempted using Array<Array<[numb ...

Designing a unique CSS border for custom list item bullets

I'm currently exploring the possibility of implementing a CSS border around an image that I have imported as a custom bullet for my list items: ul { list-style: none; margin-right: 0; padding-left: 0; list-style-position: inside; } ul > ...

Tips for minimizing database queries for each data type

I'm currently developing an App that requires the user to input numbers into two different fields. The first field is for entering numbers, while the second field displays a calculation based on the input. Each time the user enters a number, a call to ...

A guide to troubleshooting the "Cannot resolve all parameters error" in Angular

Recently delved into the world of angular 2, and I've come across my first challenge. I'm trying to establish a service for retrieving data from a server but I keep encountering this particular error Error: Can't resolve all parameters fo ...

Unable to transfer Base64 encoded data to C# through AJAX

I'm facing an issue where a base64 string I send through ajax to an aspx page with C# code behind always arrives empty. Despite other form fields posting successfully, this particular string is not making it through. The base64 string in question app ...

Javascript does not have the capability to interact directly with HTML code

I am facing an issue with my JSP code that is supposed to validate password and confirm password before submitting the form to a Java servlet. The problem is, even though I have written the validation script, it does not show alert messages or focus on t ...