Translator: KING

The original link

CSS implements triangles, not hacks

2017.3.20

Anyone who has written HTML upvote arrow, Speech bubble, or other similarly pointed elements knows that in order to create a triangle with a pure CSS implementation, you have to use certain hacks. The two most popular are implemented via borders, or Unicode characters.

Admittedly, these CSS hacks are very clever, but they are not good solutions, and the code is not elegant and flexible enough. For example, we can’t use a background image on a triangle because borders and characters can only use colors.

The speech bubble is shown below:

Use the Clip – path

Clip-path is one of the new properties in the CSS specification that allows us to show only part of an element and hide the rest. Its working principle is as follows:

Suppose we have a normal rectangular div element. You can click Run in the editor below to Run and see the rendered HTML. (There is an online code editor for you to copy and test.)

div {
    width: 200px;
    height: 200px;
    background: url(https://goo.gl/BeSyyD);
}
Copy the code
<div></div>
Copy the code

To implement triangles, we need to use the polygon() function. The parameters are comma-separated plane coordinate points that define the shape of our clipping mask. Triangle is equal to 3 points. Try changing the value and see how the shape changes.

div { width: 200px; height: 200px; background: url(https://goo.gl/BeSyyD); /* Polygon (50% 0, 0 100%, 100% 100%); /* Polygon (50% 0, 0 100%, 100% 100%); }Copy the code
<div></div>
Copy the code

Everything in the created path is preserved, and everything outside the path is hidden. In this way, we can make not only triangles, but also various irregular shapes that look like normal CSS blocks. (CSS properties can be used on these shapes)

The only drawback to this method is that we need to calculate the coordinates of the points ourselves to get a nice triangle.

However, it is better than using borders or ▲.

Browser support

If you look at the Clip-path caniuse page, at first it looks like compatibility is pretty bad, but in fact it works fine in Chrome and doesn’t need a prefix, and in Safari you need the -webkit- prefix. Firefox 53 or later is available. IE/Edge is always not supported, but it may be supported in the future.

Read more

There are a number of tips on the clip-path property, including the “magic” use of SVG. To learn more, check out the links below.

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