Vrajesh Doshi
Vrajesh Doshi

Reputation: 764

Value of x and y of SVG text as percentage + pixel

I need to virtually divide the svg element into 9 equal grids for text positioning, like x=0, y=10; x=33.33%, y=10; x=0, y=33.33% + 10 and so on. The last one in css can be done using calc(33.33% + 10) but how do I set it for the x and y of svg text. Is there a way to add percentage to pixel and assign it x and y of svg text or is there an alternative better way to proceed ahead. Please guide.

Upvotes: 2

Views: 2272

Answers (1)

ccprog
ccprog

Reputation: 21821

You need to have a place where you can use percentage values, and another where you can use pixel values. For the case of text elements, this is relatively easy. Position the text with percentage x/y values, and then move it with a transform attribute, which takes unitless numbers interpreted in the local coordinate system:

<svg>
    <text x="33.3%" y="0%" transform="translate(0, 10)"></text>
    <text x="0" y="33.3%%" transform="translate(5, 15)"></text>
<svg>

If the texts are always in the same place in relation to the grid, you could simplify:

<svg>
    <g transform="translate(0, 10)">
        <text x="33.3%" y="0%"></text>
        <text x="0" y="33.3%%"></text>
    </g>
<svg>

In more general cases the best and most semantic strategy might be to nest <svg> elements, where the inner elements represent single cells in the grid:

<svg>
    <!-- width and height are not strictly needed for the nested
         svg elements, they default to 100% -->
    <svg x="33.3%" y="0%" width="33.3%" height="33.3%">
         <text x="0" y="10"></text>
         <circle cx="50" cy="20" r="20" />
    </svg>
    <svg x="0%" y="33.3%" width="33.3%" height="33.3%">
         <text x="0" y="10"></text>
         <rect x="0" cy="0" width="100" height="50" />
    </svg>
</svg>

Upvotes: 2

Related Questions