Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SVG element width and height set in html but appearing as 0 0 in inspector

I have an 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 inspect the second rect with Chrome it has no width and height. enter image description here There are no CSS rules applying to it. Why doesn't it get affected by width and height?

like image 869
user3162553 Avatar asked Apr 29 '16 20:04

user3162553


People also ask

How do I make SVG fit inside a div?

“In the SVG declaration after the doctype, simply remove the width and height attributes. This forces the browser to always fill the containing DIV or box with your SVG.”

Why does my div have no height?

The reason why the height or the containers is 0 is because you are floating all the content inside them and floated elements don't expand the height (or width) of their parents. As you are floating all elents in row it has 0 height and therfore so has .

How does SVG reduce height and width?

❓ How can I resize a SVG image? First, you need to add a SVG image file: drag & drop your SVG image file or click inside the white area to choose a file. Then adjust resize settings, and click the "Resize" button. After the process completes, you can download your result file.


1 Answers

It works fine.

If the snippet works individually but size of div containing it in you code appears 0x0 then look into : Why is my div's height zero

Its usually caused when float is 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>
like image 63
Ani Menon Avatar answered Oct 05 '22 13:10

Ani Menon