Finally! CSS Triangles Without Ugly Hacks
Anyone who has tried to make HTML upvote arrows, speech bubbles or other pointy elements, knows that in order to create a CSS-only triangle you have to use some sort of hack. The two most popular solutions are to create your triangles out of borders, or to use unicode characters.
We have to admit that both these CSS hacks are pretty clever but they still are terrible solutions, and as such make our code much uglier and less flexible. For instance, we can’t have a triangle with a background image, since borders and characters can only be one color.
Clip-path is a fairly new addition to the CSS spec that allows us to show only part of an element and hide the rest. Here is how it works:
Let’s say we have an ordinary rectangular
div element. You can click Run in the editor below to view the rendered HTML.
To make a triangle we will need the
polygon() function. It expects as argument comma separated 2D points which will define the shape of our mask. A triangle = 3 points. Try and change the values to see how the shape transforms.
Everything inside the path we created stays, everything outside it is hidden. This way we can make not only triangles, but all sorts of asymmetrical shapes that will behave like regular CSS blocks.
The only drawback of this technique is that we have to carefully calculate the coordinates of our points in order to get a good looking triangle.
Still, it’s way better than using borders or ▲.
If you open the caniuse page for clip-path things don’t look very good at first sight, but in reality the property works perfectly fine unprefixed in Chrome and with the
-webkit- prefix in Safari. Firefox users have to wait till version 53. IE/Edge is behind the curve as usual but we can expect support sometime in the future.
clip-path property has many other tricks up its sleeve, including some SVG magic. To find out more about it check out the links below.