Home > Blockchain >  offset (using transform) svg element relative to its own size
offset (using transform) svg element relative to its own size

Time:10-05

I want to offset SVG element relative to its own size using translate with percentage, very similarly to how offset div using transform: translate(100%,0) would work:

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 enter image description here good, the circle offset was relative to its own size

while 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>

will cause this to render: enter image description here

It's basically being offset relative to the size of the svg canvas(that I never explicitly set): enter image description here

why does transform: 'translate(100%,0)' work relative to self in div html elements but relative to parent on SVG elements?

already tried:

  • wrapping g elements, or svg elements similar to other answers on this site.

want to avoid:

  • I could potentialy solve this by using .getbBox() function and calculate dimensions manually and save it to state and then offset by pixels, but I really want to avoid it and am looking for a simpler solution.

Demo

https://codesandbox.io/s/svg-vs-div-transform-translate-o2ii7

CodePudding user response:

You should set the transform-box to fill-box. For React you use camel case so it looks like this:

style={{ transform: "translate(100%,0px)", transformBox: "fill-box" }}
  • Related