Jump to content


Changing the width of an SVG rect

Moderator Tag
Go to solution Solved by mvaneijgen,

Recommended Posts

I have a simple svg with a rect box inside. I want to change the width of this rect in such a way that it changes from the centre of the rect, like a scaleX would work with transform-origin center. Currently, reducing the width contracts it from the right side. I need to change with width in order to maintain fidelity otherwise I'd use scale. Is there a way to get this to work? Would I have to play around with the x attribute? Thanks.

See the Pen yLVaXpy?editors=1000 by ritwikvd (@ritwikvd) on CodePen

Link to comment
Share on other sites

Is this what you are looking for?

See the Pen NWbRyGv by mvaneijgen (@mvaneijgen) on CodePen


I've removed with `width` and `height` from the SVG, add the `viewbox` and add `preserveAspectRatio="none"` to it. In the Rect i've set the stroke to `vector-effect="non-scaling-stroke"` so it keeps it original width. Then with GSAP I change the `width` of it.  

  • Like 2
Link to comment
Share on other sites

@mvaneijgen thanks very much for your reply. I would like the svg to remain stationary, and just the rect inside to contract and expand around its centre. 

Link to comment
Share on other sites

  • Solution

I see you've updated your pen, it is much clearer now what you want to do, would be nice if you add the GSAP code you would think you would need, then we can see your thought process. 


This is the closes I can get 

See the Pen RwoGJmg by mvaneijgen (@mvaneijgen) on CodePen


Maybe you could explain what you are trying to do? Now we know only the end goal but if we know the context maybe there is an easier solution.



  • Like 4
Link to comment
Share on other sites

Going forward, could you please use the "fork" button when making new versions of your demo to post in these forums, @volls? That way context is not lost for other readers.

Link to comment
Share on other sites

@mvaneijgen thanks! I essentially wanted to find out if there was a way to do this without having to manipulate the x attr. But I've been researching stuff thru out the day, and haven't found anything, so I think I'll just go with your solution for now. Thanks very much for your time.


@mikel Cheers! will look into that


@ZachSaucier will do!

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.