Search code examples
svghovertransformscaletranslate

Use transform with scale and translate together on a svg path


I've read several threads on this topic and maybe there are some answers out there. Whether I didn't understand it or it just doesn't suit my problem this is my question:

I have a path (inside a SVG) that I want to apply a hover on it and expand from its center. Then I thought several options (like animation with keyframes or using the DOM). I tried to solve it using transform but then if I use scale() it moves the coords of my path far away from its center and if I try to reposition my path using translate() ​it doesn't recognize both operations.

I have tried using "transform-origin: center;" (like someone's answer on another thread) but it changes anything. The only way that I can apply both is ​by using transform inside the path tag with the scale and translate together. But in that case, I can't apply the hover.

Sorry if there's an answer already. I copy an example of a simple box inside a SVG tag in order to avoid copying all the code. In this example that I'm writing down, I can't even use the scale operation.

<head> 
    <style>
        ​#sbox {​
            transition-duration: 2s
        }
        ​
        ​#sbox:hover {​
            transform: scale(2) translate(-50,-50);
        }

    </style>

</head>
  
<body> 
    <svg id="svg1" x="0px" y="0px" viewBox="0 0 1200 1200">
        <path id='sbox' d="M 264.9 271.3 L 343.3 271.3 L 343.3 396.1 L 264.9 396.1 L 264.9 271.3 Z" fill='blue'/>
    </svg>
</body>

Now I uploaded a photo to show what happens when I only scale (the blue box is the initial bounding box). It doesn't expand from its center.


Solution

  • You can use transform-origin and transform-box to centre on the rect's shape.

    #sbox {
        transition-duration: 2s;
        transform-origin: center;
        transform-box:fill-box;
    }
    
    #sbox:hover {
        transform: scale(2);
    }
        <svg id="svg1" x="0px" y="0px" viewBox="0 0 1200 1200">
            <path id='sbox' d="M 264.9 271.3 L 343.3 271.3 L 343.3 396.1 L 264.9 396.1 L 264.9 271.3 Z" fill='blue'/>
        </svg>