How do CSS triangles work?

If you've been doing CSS for awhile you either seen them or used them. But do you know why the technique works? The code after all, is not very intuitive:

See the Pen CSS triangle by dpiatek (@dpiatek) on CodePen.

To understand how the code works, we need to know how adjacent borders edges look on an element. Now, quite often these borders are used sparringly, with the same color, so many developers aren't actualy aware that borders connect at an angle:

See the Pen CSS borders by dpiatek (@dpiatek) on CodePen.

Now, if we remove the width and height (note I've changed the thickness of the borders):

See the Pen CSS borders, collapsed by dpiatek (@dpiatek) on CodePen.

The connections are at an angle, so when we collapse the contents of an element, we can manipulate the 4 triangles. To create a tip, we need to remove the border on that side and make the adjacent ones transparent. So for a "upwards" pointing triangle we remove the border-top and make border-left and border-right transparent.

See the Pen CSS borders size collapsed, one-side transparent, top removed by dpiatek (@dpiatek) on CodePen.

Playing around with these values we can see that the border that is opposite to "tip" will control the height, and the adjacent borders will control the length of the sides. Remember also that the actual center of the element you are controlling will be on the "tip".

So if you ever have trouble with these, or are maybe building more complex shapes you can always come back to the "full" border shape and create your triangle from there.