by
on
under
Permalink

Scaling SVG Clipping Paths for CSS Use

A legit CSS trick documented by Eric Meyer!

So there is polygon() in CSS and in SVG. They are closely related, but there are all kinds of weirdnesses . For example, you can use path() in CSS to update the d attribute of a , but you can’t do the same with polygon() and .

Part of the problem is that polygon() in CSS only accepts numbers with units, like px, %, em, or whatever.

.clip-me {
  /* Works! */
  clip-path: polygon(50% 0, 100% 25%, 100% 75%, 50% 100%, 0 75%, 0 25%);

  /* Does NOT work */
  clip-path: polygon(50 0, 100 25, 100 75, 50 100, 0 75, 0 25);
}

Which is exactly the opposite in SVG:


  /* Works! */
  

  /* Does NOT work */
  
  

The trick is that you can force the SVG coordinates to behave like percentage coordinates (even with weird viewBoxes) with some light math, a transform attribute, and a special clipPathUnits attribute.


  
    
  

Those two values are 1/329.6667 and 1/86, respectively, and they effectively scale every point in the d attribute to fit into the needed 0–1 range. Thus we have an SVG clipping path that scales with the element and fits to its dimensions!

Direct Link to ArticlePermalink


Scaling SVG Clipping Paths for CSS Use is a post from CSS-Tricks

Original Article From CSS Tricks

Leave a Reply

Your email address will not be published. Required fields are marked *