Search code examples
htmlsvg

SVG stroke width expand inside bounding rectangle


I have begun working with SVGs and have (quickly) hit a road block.

I am trying to find a way to add a border around a rectangle but for it to only "expand" inside. Currently I am just drawing a path around the rectangle and using stroke width. This has the desired effect of showing a "filling" animation when used with css transition. But I don't want it to expand outside of the bounds of the rectangle. See images

enter image description here

with path

enter image description here

As you can see the stroke width is going in both directions, outside of the bounding rectangle and inside. How would I get rid of the outside bit?


Solution

  • Draw the <rect> within an inner <svg> element which is the same size as the <rect>. The inner <svg> element will clip the <rect>.

    You can also do this with a clip-path or a clip if you want but the inner <svg> way is simpler.