The previous answers gave poor results when using rounded corners or stroke-width
that's >1 . For example, you would expect the following code to produce a rounded rectangle, but the corners are clipped by the parent svg
component:
<svg width="200" height="100">_x000D_
<!--this rect should have rounded corners-->_x000D_
<rect x="0" y="0" rx="5" ry="5" width="200" height="100" stroke="red" stroke-width="10px" fill="white"/>_x000D_
<text x="50%" y="50%" alignment-baseline="middle" text-anchor="middle">CLIPPED BORDER</text> _x000D_
</svg>
_x000D_
Instead, I recommend wrapping the text
in a svg
and then nesting that new svg
and the rect
together inside a g
element, as in the following example:
<!--the outer svg here-->_x000D_
<svg width="400px" height="300px">_x000D_
_x000D_
<!--the rect/text group-->_x000D_
<g transform="translate(50,50)">_x000D_
<rect rx="5" ry="5" width="200" height="100" stroke="green" fill="none" stroke-width="10"/>_x000D_
<svg width="200px" height="100px">_x000D_
<text x="50%" y="50%" alignment-baseline="middle" text-anchor="middle">CORRECT BORDER</text> _x000D_
</svg>_x000D_
</g>_x000D_
_x000D_
<!--rest of the image's code-->_x000D_
</svg>
_x000D_
This fixes the clipping problem that occurs in the answers above. I also translated the rect/text group using the transform="translate(x,y)"
attribute to demonstrate that this provides a more intuitive approach to positioning the rect/text on-screen.