How can I offset an SVG element relative to its own size using translate with a percentage, similar to how we would offset a div using transform: translate(100%,0)
? Here is an example:
This code:
<div style={{ overflow: 'visible', position: 'relative' }}>
{/* rect */}
<div style={{ height: 20, width: 20, background: 'black', position: 'absolute' }} />
{/* circle */}
<div
style={{
height: 20,
width: 20,
background: 'purple',
borderRadius: '50%',
position: 'absolute',
transform: 'translate(100%,0)',
}}
/>
</div>
will look like this: https://i.sstatic.net/q4m0W.png. The circle offset is relative to its own size.
However, in this case:
<svg overflow={'visible'}>
<rect width={20} height={20} />
<circle cx={10} cy={10} r="10" fill="purple" style={{ transform: 'translate(100%,0px)' }} />
</svg>
the result will be different: https://i.sstatic.net/JpTAS.png.
The issue here is that the circle is being offset relative to the size of the svg canvas, which was never explicitly set: https://i.sstatic.net/KjgcM.png.
So, why does transform: 'translate(100%,0)'
work relative to self in div html elements but relative to parent on SVG elements?
I have already tried wrapping g
elements or svg
elements as suggested in other answers, but no luck.
Instead of manually calculating dimensions using .getbBox() function and offsetting by pixels, I am looking for a simpler solution. Any ideas?
Demo
https://codesandbox.io/s/svg-vs-div-transform-translate-o2ii7