marielle
marielle

Reputation: 428

Understand SVG viewport

I'm trying to understand the SVG viewport. Why are these three examples so different?

svg {
  border: 2px solid red;
}
<div>

  <svg>
    <rect x="0" y="0" width="100" height="100" fill="blue" />
  </svg>

  <svg width="200" height="200">
      <rect x="0" y="0" width="100" height="100" fill="blue" />
  </svg>

  <svg viewBox="0 0 200 200">
      <rect x="0" y="0" width="100" height="100" fill="blue" />
  </svg>

</div>

Upvotes: 0

Views: 62

Answers (1)

Robert Longson
Robert Longson

Reputation: 123995

  • The first example is missing a width and height. The CSS specification says that replaced elements missing width and height values fallback to 300px x 150px so you'd see the top left 300 x 150 px of whatever you're drawing onto the canvas.

  • The second example has width and height so you'd see that part of the canvas.

  • The third example also has no width/height but oddly we're now going to use the 100% x 100% lacuna values for the width/height because we have a usable aspect ratio from the viewBox. The viewBox also scales the 200 x 200 internal co-ordinate system to fix into that canvas so everything looks bigger.

Upvotes: 2

Related Questions