How can I limit or clip text in SVG?

As Marcin said in point (2) of his answer (unfortunately downvoted but actually this is a good point) an alternative way to achieve the effect is to overpaint the part not wanted with a white rectangle.

<!DOCTYPE html>
<html>
<body>
<svg>
<text x="100" y="100">Orange</text>     
<text x="100" y="115">Pear</text>       
<text x="100" y="130">Banana</text>     
<text x="100" y="145">Pomegranate</text>

<!-- Overpaint the overflowing text -->
<rect x="155" y="85" width="100" height="100" fill="white" />

<line x1="157" y1="85" x2="157" y2="155" style="stroke:rgb(100,100,100)"/>

<text x="160" y="100">12</text>
<text x="160" y="115">7</text>
<text x="160" y="130">9</text>
<text x="160" y="145">2</text>

</svg>
</body>
</html>

svg overlay sample

Reference to the SVG specification: SVG 2.0 Rendering Order


If for some reason you don't want to use clipping, you can also use a nested SVG tag:

<svg>
  <svg x="10" y="10" width="10" height="10">
    <text x="0" y="0">Your text</text>
  </svg>
</svg>

This way, your text will be cut off when it's outside the nested SVG viewport. Note that the x and y of the text tag refer to the coordinate system of the nested SVG, and correspond to 10 in the coordinate system of the outer SVG.


You can use clip-path to clip to whatever shape you want, see e.g masking-path-01 from the svg testsuite.

Relevant parts, defining the clip path:

<clipPath id="clip1">
  <rect x="200" y="10" width="60" height="100"/>
  ... you can have any shapes you want here ...
</clipPath>

and then apply the clip path like this:

<g clip-path="url(#clip1)">
  ... your text elements here ...
</g>

Tags:

Html

Svg