Chris Roberts

Drawing Triangles with HTML and CSS

• Posted in Programming

One of the great things about working with a team of creative designers and developers is that I get exposed to more new techniques and tools than I'd ever have time to find for myself.

One example of this is a something that Joe Sergeant showed me the other day - a technique to draw triangles using nothing more than HTML and CSS. "But how", I hear you say, "do you draw a triangle with a box model?!".

Let me show you...

<html>
  <head>
    <style type="text/css">
      div#triangle
      {
        width: 0;
        height: 0;
        border-style: solid;
        border-width: 25px;
        border-color: transparent transparent #000 transparent;
      }
    </style>
  </head>
  <body>
    <div id="triangle" />
  </body>
</html>

This code snippet renders a page that looks like this.

Triangle

A pretty neat trick, I'm sure you'll agree. But how have we managed to turn a box into a triangle? It's all down to the way borders are rendered in the browser.

Box Model Border Rendering

Drawing a box, you might imagine, is as simple as drawing 4 lines.

Box with 1 pixel border

But what happens if we want to draw the same box with a 20 pixel wide border? You might think that you simply draw the same 4 lines, but 20 pixels wide. If you did, this is what you'd get (I've changed the border colours so that you can more easily see what's going on).

Box with 20 pixel border and no end-caps

As you can see, the corners of the box clearly don't look as you'd expect (because that isn't actually the way browsers render them!). In order to make sure the border renders properly, the browser adds extra sections to the end of each line.

Box with 20 pixel border and end-caps

It is this feature that we're exploiting in our CSS trickery above. By making 3 of the 4 borders transparent, you're left with a line which is 'capped' by two triangular sections. Reducing the width of the box to zero then brings these two end caps together to form a larger triangle.

Box with 20 pixel border and zero width

To adjust the direction of the triangle, simply set the colour on a different edge of the border.

I love the elegance and simplicity of this method. It's one less image that the browser will have to download and it will scale perfectly if a user zooms in on the page. What's more, in the hands of a talented designer like Joe, you can produce some great looking results...

Example breadcrumb trail