Skip to content Skip to sidebar Skip to footer

Svg Fill Width To Child Elements

I'd like my container SVG element to scale in order to fit its child group elements or for it to present scrollbars on overflow. I was wondering if there was a css property in orde

Solution 1:

remove width and height from the <svg> and add an viewBox attribute instead. Addionally you need a preserveAspectRatio attribute with a value of your desired behavior.

For more detailed information have a look here. This method uses the SVG viewport which is a bit complicated at the first glance, but in effect, this separates the visible dimensions from the graphical setup of the graphic. This way the <svg> receives its width and height from the context it lives in, from the css in your case.

It took me a while to understand that concept, but once you got it you will notice that gives you a lot flexibility, what is actually much more than with pixel images.

Solution 2:

Not sure if this solves your problem or not, but you could put the constraints on svg's parent tag (the div tag).

Something like this:

<divclass="wrapper"><svgclass="main"xmlns="http://www.w3.org/2000/svg"><g><rectx="20"y="20"height="250"width="400"style="fill:#006600"/></g></svg></div>

.wrapper {
    width: 200px;
    height: 100px;
    overflow: scroll;
}
.main {
    width: 400px; 
    height: 250px;
}

Here's a jsfiddle.

Solution 3:

There is no way to have the SVG automatically update its width and height when you add elements to it. All you can do is manually update the width and height yourself.

However, rather than having to remember to update the SVG width and height every time you add something, you could add an interval timer function to do the check for you.

setInterval(mySVGCheckFn, 500);

functionmySVGCheckFn() 
{
    var  svg = document.getElementById("mysvg");
    var  bbox = svg.getBBox();

    // Add 10 padding for some breathing space    
    svg.setAttribute("width", bbox.x + bbox.width + 10);
    svg.setAttribute("height", bbox.y + bbox.height + 10);
}

Demo here

Click 'Add more' to add random circles to the SVG.

DOM2 added some event types that are supposed to be fired when you add nodes to the DOM. They would be the ideal solution, however I believe they aren't supported reliably across all browsers.

Post a Comment for "Svg Fill Width To Child Elements"