Andrey Bushman
Andrey Bushman

Reputation: 12476

Why the `svg` size and the circle `stroke-width` are not like expected?

Google Chrome 60.0.3112.90

I learn SVG. Why the svg real size is not 10cm x 10cm, the circle stroke-width is not 1pt and radius are not 2.5cm?

.svg-container, .canvas{
	margin: 0;
	padding: 0;
	width: 10cm;
	height: 10cm;
	background-color: green;
}

.geometry {
	stroke: gray;
	fill: yellow;
	stroke-width: 1px;
}
<div class='svg-container'>
  <svg class='canvas' viewBox='0 0 10 10'>
    <circle class='geometry' cx='5' cy='5'
      r='2.5'/>
  </svg>
</div>

Upvotes: 2

Views: 3063

Answers (1)

Terry
Terry

Reputation: 66103

First of all: never trust the browser to generate true physical sizes specified in stylesheets on the screen.

Note that you have declared your viewBox to be 0 0 10 10, meaning that it is 10 units across and 10 units tall. All the units applied to SVG elements within this will be rendered relative to the viewBox dimensions, i.e. a stroke-width: 1px on the circle will be rendered as 1/10 the width of the viewBox. Taking away the viewBox attribute will force things to be rendered in absolute pixels.

In the example below, I have set the svg width to 200px for illustrative purposes. When viewBox="0 0 10 10" is used, all the units will be measured relative to this dimension:

  • Stroke width of 1px will mean (200 ÷ 10) × 1 = 20px
  • Radius of 2.5 will mean (200 ÷ 10) × 2.5 = 50px

Just remember that when viewBox it set, it controls how contents are set within its own coordinate system: and that is scaled up/down into actual pixels on the screen, depending on the width and height of the <svg> element. A better explanation is offered here: svg viewBox attribute

.svg-container, .canvas{
	margin: 0;
	padding: 0;
	width: 200px;
	height: 200px;
	background-color: green;
}

.geometry {
	stroke: gray;
	fill: yellow;
	stroke-width: 1px;
}
<div class='svg-container'>
  <!-- Viewbox forces all units to be relative to its dimensions -->
  <svg class='canvas' viewBox='0 0 10 10'>
    <circle class='geometry' cx='5' cy='5'
      r='2.5'/>
  </svg>
</div>

<br />

<div class='svg-container'>
  <!-- Without viewbox, all units are rendered in px -->
  <svg class='canvas'>
    <circle class='geometry' cx='50' cy='50'
      r='25'/>
  </svg>
</div>

Upvotes: 4

Related Questions