Pedro Henrique
Pedro Henrique

Reputation: 782

Center SVG viewbox X and Y based on content

Let's say I have the following SVG:

 <svg width="640" height="480" viewbox="0 0 640 480" style="border: 1px dotted black;">
		<line x1="0" y1="0" x2="100" y2="0" stroke="black"></line>	
		<line x1="100" y1="0" x2="100" y2="100" stroke="black"></line>	
		<line x1="100" y1="100" x2="0" y2="100" stroke="black"></line>	
		<line x1="0" y1="100" x2="0" y2="0" stroke="black"></line>	
	</svg>

This draws a square in the top left corner of the SVG.

If I want to move the viewbox so the square is centerd, I can change the viewbox X and Y like this:

<svg width="640" height="480" viewbox="-270 -190 640 480" style="border: 1px dotted black;">
		<line x1="0" y1="0" x2="100" y2="0" stroke="black"></line>	
		<line x1="100" y1="0" x2="100" y2="100" stroke="black"></line>	
		<line x1="100" y1="100" x2="0" y2="100" stroke="black"></line>	
		<line x1="0" y1="100" x2="0" y2="0" stroke="black"></line>	
	</svg>

My question is, can the same result be achieved without changing the viewbox X and Y nor the lines Xs and Ys?

Upvotes: 0

Views: 426

Answers (1)

Paul LeBeau
Paul LeBeau

Reputation: 101810

Yes. Use a transform (as @sean suggested).

<svg width="640" height="480" viewbox="0 0 640 480" style="border: 1px dotted black;">
  <g transform="translate(270, 190)">
    <line x1="0" y1="0" x2="100" y2="0" stroke="black"></line>	
    <line x1="100" y1="0" x2="100" y2="100" stroke="black"></line>	
    <line x1="100" y1="100" x2="0" y2="100" stroke="black"></line>	
    <line x1="0" y1="100" x2="0" y2="0" stroke="black"></line>
  </g>
</svg>

Upvotes: 1

Related Questions