Home > other >  Setting width height of svg inside svg
Setting width height of svg inside svg

Time:07-02

I am making an svg file. The svg has an svg inside it. I tried to set the width and height of the inner svg, but the svg width and height stayed at 0. I found this out from the inspect panel.

<svg width="100%" height="100%" viewbox="0 0 100 100">
  <svg width="40" height="40" viewbox="30 30 40 40"></svg>
</svg>

This is what the code snippet above looks like with the inspect panel. 0x0 svg If I put an object inside, lets say, a 10x10 rectangle, it looks like this (snippet below).

<svg width="100%" height="100%" viewbox="0 0 100 100">
  <svg width="40" height="40">
    <rect x="0" y="0" width="10" height="10"></rect>
 </svg>
</svg>

The above snippet viewed from the inspect panel. bad svg

From the inspect panel, you can see, I can't set the width, height, x, or y position of the svg using the width, height, or viewbox attributes. Is there any way I can set the width and height of the svg regardless of the svg's children?

CodePudding user response:

Pay attention to the correct spelling: It's "viewBox" (camelCase).

But it's true when inspecting a nested <svg> in devtools the bounding box dimensions will be calculated based on the actual child elements.

However, all child elements will be positioned according to the viewBox - just as expected:

svg{
  display:block;
  border:1px solid #ccc;
}
<svg  width="200px" height="200px" viewBox="0 0 100 100">
  <svg  x="0" y="0" width="50" height="50" viewBox="0 0 50 50">
    <circle cx="100%" cy="100%" r="25%" fill="green"/>
  </svg>
</svg>

<svg  width="200px" height="200px" viewBox="0 0 100 100">
  <svg  x="50" y="50" width="50" height="50" viewBox="0 0 50 50">
    <circle cx="0%" cy="0%" r="25%" fill="green"/>
    <circle cx="100%" cy="0%" r="25%" fill="green"/>
    <circle cx="100%" cy="100%" r="50%" fill="red"/>
  </svg>
</svg>

  •  Tags:  
  • svg
  • Related