Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SVG element appears to have arbitrary height

Tags:

html

svg

I've been really trying to learn some SVG. But browsers seem to get in a right old muddle rendering it.

Take the following HTML:

<html>
  <head></head>
  <body>
    <svg xmlns="http://www.w3.org/2000/svg" xlink="http://www.w3.org/1999/xlink">
      <rect height="100" width="100" style="stroke:#006600; fill: #00cc00"/>
    </svg>
    <p>Hello? Hellooooooooooooo?</p>
  </body>
</html>

View this is any modern browser and you'll see an arbitrary amount of whitespace between the rectangle and the following HTML paragraph. (IE9 doesn't display anything but noone will be surprised about that.)

Firefox (Firebug) doesn't give the heights of either the svg or the rect elements. It just wimps out and says 'auto'.

Opera says the svg has a height of 150px and says 'auto' for the rect.

Chrome mans up and gives heights for both. 102px for the rect (obviously including the stroke) and 428px for the svg.

My expectation is that the svg element would be a 'thin' container (i.e. add nothing to the dimensions of its contents) and therefore have a height of 102px.

Anyone know what the correct behaviour should be and how I might go about fixing this?

like image 322
David Avatar asked Jan 01 '12 23:01

David


1 Answers

You've not explicitly defined what the width or height of the SVG is, or where the rectangle is placed, or even what part of the SVG is of interest. It's hardly surprising browsers are dealing with things differently.

Try defining a width and height:

<svg xmlns="http://www.w3.org/2000/svg" xlink="http://www.w3.org/1999/xlink" width="102px" height="102px">
  <rect height="100" width="100" style="stroke:#006600; fill: #00cc00"/>
</svg>

Alternatively, define a viewBox:

<svg xmlns="http://www.w3.org/2000/svg" xlink="http://www.w3.org/1999/xlink" viewBox="0 0 102 102">
  <rect height="100" width="100" style="stroke:#006600; fill: #00cc00"/>
</svg>

Or both:

<svg xmlns="http://www.w3.org/2000/svg" xlink="http://www.w3.org/1999/xlink" viewBox="-50 -50 52 52" width="102px" height="102px">
  <rect height="100" width="100" style="stroke:#006600; fill: #00cc00"/>
</svg>

Here are some examples in action.

like image 160
robertc Avatar answered Nov 16 '22 07:11

robertc