All Shapes Are Beautiful

Experimenting with CSS clip-path.

Tagged with: programming, web

Published on and last updated on

This post contains some CSS style demonstrations which may only work in recent versions of modern browsers. A feed reader, Lynx, or Internet Explorer will probably not display this article in all its beauty.

What if I told you, that the web doesn’t have to consist only of boxes. This is something I just recently discovered after I had to build the header of a website in the shape of a trapezoid. At first, I wanted to use images to accomplish this but the site should be able to scale for multiple resolutions which made this approach quite difficult. After some research, I found out about the CSS clip-path property. This property makes it possible to define basic shapes like polygons, ellipses, or circles. When a clip-path is applied to an element only the defined region of the element is visible. Most modern browsers support clip-path. To see which browsers should work you can take a look at the following “Can I use…” table. Below you should see three elements that are shaped like a circle, a diamond, and an ellipse.

These are not images but actual div elements. I apply one of the following classes to each of the elements to clip them into the right shape.

.circle {
  clip-path: circle(50% at 50% 50%);
}
.diamond {
  clip-path: polygon(50% 0, 100% 50%, 50% 100%, 0 50%);
}
.ellipse {
  clip-path: ellipse(25% 40% at 50% 50%);
}

It is quite nice to be able to transform elements into simple shapes but the real power of clip-path is that it can use SVG to define what should be clipped away. In the image below you can see my cat. An SVG clip-path of a brushstroke is applied to it which gives the image a creative border.

The code to use an SVG as a clip-path is very similar to the simple shapes above. A SVG clipPath element is referenced by id via the url('#cat-clip-path') function. The referenced SVG is included in the source code of this post.

.cat {
  clip-path: url("#cat-clip-path");
}

To find out more about CSS clip-path I recommend that you look at the guides provided by MDN. A nice tool that can help to build clip paths is Clippy. I hope this article offered an interesting introduction to the CSS clip-path property and why it is pretty awesome.