How to create triangles using CSS easily

We often see some tooltips that uses triangular arrows to emphasize the content and images were often used for the arrows. Now, with new techniques, we can create these arrows in CSS just fine.

Here’s an example:

CSS equilateral triangle

 

We’ll use CSS borders to create the triangles. You may ask, “Why can borders do that?”. It’s because browsers draw borders as triangles and we can use that to make triangles.

First, as the borders are drawn around the container we need to make sure the container has no width & height (i.e. set them to zeros).

HTML:

<div id="triangle"></div>

CSS:

#triangle {
    width: 0;
    height: 0;
}

Then, we need to add borders in. In order to aid the creation of triangles, we need to add colours to all sides. It’ll now look like this:

Triangles diagram

 

CSS:

#triangle {
    border-top: red 2em solid;
    border-bottom: green 2em solid;
    border-left: blue 2em solid;
    border-right: orange 2em solid;
}

You can now see 4 triangles showing up. By adjusting the thickness of each side of border, you can create different types and sizes of triangles. Examples are:

Triangles example 3Triangles example 2