The width and height of the SVG element are set in html, but are displayed as 0 0 in the inspector

I have svg rect like this:

<svg class="legend-square"> <defs> <pattern id="pattern1" width="3" height="3" patternunits="userSpaceOnUse" patterntransform="rotate(-45)"> <rect width="2" height="3" transform="translate(0,0)" fill="purple"></rect> </pattern> </defs> <rect width="12" height="12" fill="url(#pattern1)"></rect> </svg> 

When I check the second rectangle with Chrome, it has no width and height. enter image description here CSS rules do not apply to it. Why is this independent of width and height?

+5
source share
2 answers

You really have not provided enough information. For example, what is the parent of your SVG?

Just because your <rect> has a width and a height does not mean what your SVG does. SVG is not like HTML, where elements expand to fit their children. SVG is similar to the <canvas> . You must make sure that it explicitly (or implicitly) has a size.

You did not specify width and height attributes for your <svg> element, so both defaults are set to "100%". The fact that they are 100% dependent on what size is the parent element of the SVG. Hence my first question above.

+1
source

It works great.

If the fragment works individually, but the size of the div containing it, the code 0x0 appears, and then look at: Why is my div height zero

It usually occurs when a float set.

 <div> <svg class="legend-square"> <defs> <pattern id="pattern1" width="3" height="3" patternunits="userSpaceOnUse" patterntransform="rotate(-45)"> <rect width="2" height="3" transform="translate(0,0)" fill="purple"></rect> </pattern> </defs> <rect width="12" height="12" fill="url(#pattern1)"></rect> </svg> </div> 
-1
source

All Articles