How to align an object in SVG document?

noober picture noober · Dec 23, 2010 · Viewed 52.1k times · Source

Is there a way to align an object (say, rect) in SVG, relative to the right border of a group or the document? I want the object to keep its size, when I increase the whole document width, but increase X position to stay right-aligned.

Regards,

Answer

kulpae picture kulpae · Jun 12, 2011

I was looking for a way to float a < g> element to the right of a svg file with width=100%. So one could scale the image and my < g> element would stick to the right without beeing scaled.

Here is what I found out:

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> 
<svg xmlns="http://www.w3.org/2000/svg" 
    xmlns:xlink="http://www.w3.org/1999/xlink" 
    xmlns:ev="http://www.w3.org/2001/xml-events" 
    version="1.1" 
    baseProfile="full" 
    width="100%" 
    height="100%"> 

    <svg viewBox="0 0 300 300" width="100%" height="300px" 
        preserveAspectRatio="xMaxYMin meet"> 
        <g transform="skewX(45)" style="fill:red;">
            <rect x="0" y="0" height="100%" width="20px" /> 
            <rect x="270" y="0" height="100%" width="20px" /> 
        </g> 
    </svg> 
</svg> 

The trick is to use a < svg> tag, where you place your element, that you want to stick to the right border. Then you tell the < svg>-tag not to scale the inner elements and to move them so, that the x values are at their maximum and y at minimum (xMaxYMin)

preserveAspectRatio="xMaxYMin meet"

In the same way you can center it...

source: http://www.w3.org/TR/SVG/coords.html#ViewBoxAttribute