Introduction to Clipping Using clip-path in CSS

0
520

Introduction to Clipping Using clip-path in CSS

clip-path is a very interesting property that allows to clip the visible portion of SVG elements, images or any HTML element really.

At this time, clip-path still needs to be prefixed with -webkit- for it to work in Safari.

Defining Basic Shapes With clip-path

clip-path makes it easy to clip-out basic shapes using either of the polygonellipsecircle or inset keywords, which are part of the CSS exclusion module.

Polygon

Polygon is the most flexible of all the available shapes because it allows you to specify any amount of points, a little bit like an SVG path. The provided points are pairs of X and Y coordinates that can be of any unit (eg: pixel or percent-based). Because it’s the most flexible, it’s also the most complex and you’ll probably want to use a tool to define your points.

Let’s illustrate with an example. First you’ll see our starting image, then our image with a clip-path applied to get a triangle shape, followed by a more complex X-shape, and then finally a star shape:

Introduction to Clipping Using clip-path in CSS
Introduction to Clipping Using clip-path in CSS

Circle

Circles are defined with this syntax: circle(radius at posX posY). The position is optional and will default to 50% 50%. Here are two examples to illustrate:

Ellipse

Ellipses are defined using this syntax: ellipse(radiusX radiusY at posX posY). Once again, the position is optional and will default to 50% 50%. Here are two examples:

Inset

With inset you can define an inner rectangle and everything outside will be cut-out. This makes it easy to effectively crop an image or an element directly in the browser. You can also make the rectangle rounded with the round keyword and a border radius value:

Animations and Transitions

Animations and transitions can also be applied with clip-path to create interesting effects. Just make sure that all the steps in your animation contains the same amount of points. Let’s demonstrate with an example:

Here’s the CSS rules used to create this animation:

Oh, and in case you’re interested in the little script to make the start/stop button work. It’s as simple as adding or removing the animate class on our image:

Custom SVG Shapes

You can also define any arbitrary SVG shape to act as the clip-path value. You’ll obviously want to start in a tool like Sketch to create your shape and then copy the SVG markup into a text editor. In your SVG markup, simply wrap your shape in a clipPath element and wrap the clipPath in a defs block.

Something like this for example:

And now you can apply the defined shape as the clip-path value using the url keyword and the id of the SVG shape:

original