email@encode8.com
CSS

CSS Basics: How Triangles Work

If you have ever used tooltips in any of your projects, you must have noticed little triangles that point to a specific element. There are several tutorials available online that shows you how to create triangles with CSS. But none of them discusses in detail how CSS triangles work. In this tutorial I will try to explain in detail the anatomy of a CSS triangle.

What is used to create CSS triangles?

In short, borders are used in an intelligent manner to create triangles.

How do borders work in CSS?

Borders ‘butt’ each other at 45°. To demonstrate this, let’s create a div with the following:

<div class='borderTest'></div>

<style>
.borderTest {
  width:100px;
  height:100px;
  border-top:40px solid red;
  border-right:40px solid blue;
  border-bottom:40px solid black;
  border-left:40px solid green;
}
</style>

You would have this:

css border demo
As you can see the borders hit each other at 45°

What’s next?

Now, let’s make one change at a time.

  1. Remove the top-border (by border-top-width:0)
    top-border-0
  2. Set the height and width to 0 (with width:0;height:0)
    border-height-width-0
  3. Set the left and right border colors to transparent (with border-right-color:transparent;border-left-color-transparent;)
    css-triangle

So, finally we have this:

.borderTest {
  width:100px;
  height:100px;
  border-top:40px solid red;
  border-right:40px solid blue;
  border-bottom:40px solid black;
  border-left:40px solid green;
  border-top-width:0;
  width:0px;
  height:0px;
  border-right-color:transparent;
  border-left-color:transparent;
}

Or, removing the redundancies, we would have:

.borderTest {
  width:0px;
  height:0px;
  border-left:40px solid transparent;
  border-right:40px solid transparent;
  border-bottom:40px solid black;
}

To give you a visual representation, we have done this:

Conclusion

CSS triangles are widely used as :after pseudo elements. You can find them in breadcrumbs, tooltips, modal windows, help-texts. The basic idea is same. Here I showed you how to create a triangle that points upwards. You can create a right-pointed triangle by setting right-border to 0, top and bottom border to transparent, and so on.