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>