Pure CSS triangles are one of those clientside development hidden gems that few know about. Let’s take a look at what it takes to create a triangle that’s compatible across all browsers (including IE7+) using nothing more than a few lines of CSS.
Understanding the Concept
Everyone knows how to add a border to an element, nothing really shocking there. But something that many people might not know, is that browsers draw borders at an angle from the center. Using this technique to our advantage, we can set 3 border colors of an element to transparent, leaving our remaining side to render out a triangle.
Creating the Base Class
To make our triangles easy to modify, we’ll start with the base class of
.triangle that will contain the modifiable parameters to make our triangle look the way we want. This is where you can change the values to coordinate with your own application.
Nothing too exciting yet, we’ve create a basic block with a 50px solid white border. Notice that we set the width and height to 0, this is to allow the border to create our triangle without any extra spacing in the middle of our element. And finally, we add the zoom parameter to target IE7 and below and let those browsers know that this element has a layout.
Building the Triangles
Now that we have a basic 4 sided white square, we can add some subclasses to override 3 of the sides and set their border color to transparent, leaving just the remaining side and our triangle.
border-top: 0 solid transparent;
border-right: 0 solid transparent;
border-bottom: 0 solid transparent;
border-left: 0 solid transparent;
Notice that on the side our triangle is pointing, in addition to setting the border color to transparent, we also set the width to 0. This is to ensure that we don’t have any extra spacing in the empty space of our element. We want the element to only be the size of what we can see, nothing more.
Adding the Markup
Now that we have the styles for our triangles, the last thing we need to do is include the markup to display them.
<div class="triangle up"></div>
<div class="triangle right"></div>
<div class="triangle down"></div>
<div class="triangle left"></div>
Hopefully this quick tip gave you everything you need to start creating your own CSS triangles. If you’re having any troubles getting your markup and styles to play nicely, drop me a line in the comments and we’ll work on getting everything sorted out. Thanks for reading!