James McGrath

Scaling SVG clip paths.

Aug 28, 2023
2 minutes

I had to code a design that was like half a pie chart with text in the slices and the center of the chart was cut out in a circle like a donut. You can see it here on Squad by Mamamia. The solution I went with was to use SVGs as a clip path to make the background shapes.

I had to make a couple of modifications to the SVG code that I embedded.

  • Wrap the <path> in a <clipPath> element and give it an #id so it can referenced from the CSS clip-path: url(#id)
  • Add the attribute clipPathUnits="objectBoundingBox"
  • Add a transform="scale(1/svg-width, 1/svg-height)" attribute to the <path> .
  • Set the width and height attribute of the SVG to 0
<svg width="0" height="0" viewBox="0 0 148 147" version="1.1" xmlns="http://www.w3.org/2000/svg" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2;">
 <clipPath id="slice1" clipPathUnits="objectBoundingBox">
  <path transform="scale(0.00675676, 0.00675676)" d="M145.047,72.558c0,-6.11 0.927,-12.004 2.645,-17.55l-134.414,-55.008c-8.571,22.549 -13.278,47.002 -13.278,72.558c0,26.209 4.942,51.263 13.936,74.287l133.951,-56.152c-1.837,-5.717 -2.84,-11.808 -2.84,-18.135" style="fill:none;" />
 </clipPath>
</svg>

Next It’s time to do the CSS part of this.

  • Add the CSS declarations to make the clipPath visible.
  • On the parent container add a fluid typography font-size
    • The code below has a fallback for browsers that don’t support clamp()
  • Use em to size and position the shapes so that it can scale.
@media (min-width: 20em) {
  .container {
    font-size: calc(1rem + ((1vw - 0.2rem) * 5.6818));
    min-height: 0vw;
  }
}
@media (min-width: 64em) {
  .container {
    font-size: 3.5rem;
  }
}

@media(min-width: 0) {
 @supports(font-size: clamp(1px, 2px, 3px)) {
  .container {
   font-size: clamp(1rem, -0.1364rem + 5.6818vw, 3.5rem);
  }
 }
}
.shape {
 width: 6.25em;
 height: 6.25em; 
 position: relative;
 clip-path: url(#slice1);
 background: green;
}

Here’s what the finished example looks like. If you open the CodePen or resize your browser the green shape will scale.

See the Pen scalable clip path by James (@jamcgrath) on CodePen.