Finally! CSS Triangles Without Ugly Hacks

css-triangles

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.

Introducing Clip-path

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.

(Play with our code editor on Tutorialzine.com)

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.

(Play with our code editor on Tutorialzine.com)

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 ▲.

Browser Support

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.

Further Reading

The 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.

  • Clip-path on MDN – here
  • In-depth tutorial for clip-path on Codrops – here
  • Clippy, a clip-path generator – here

Tags: , , ,

This entry was posted on Monday, March 20th, 2017 at 7:02 am
Entry is filed under PHP Tutorials.
Read original posting here.
You can follow any responses to this entry through the RSS 2.0 feed.

Both comments and pings are currently closed. Total Views: 19

Comments are closed.