Wednesday, November 28, 2012

How CSS Triangles Work

Just search on "CSS Triangles" or "CSS Tooltip Triangles" and you'll see lots of posts showing how to use CSS borders to achieve a triangle.

I saw lots of pictures of triangles where I could copy the CSS but I didn't immediately grok how it worked. (I guess I don't use thick borders very often.) So here are the pictures I wish I'd seen in sequence. The first one (showing how thick borders are beveled around inner content) is the key. After that, you just imagine the inner content getting squished so that all you have left is triangles. Hope this helps.

10 pixel borders on something with content

10 pixel border on something empty

Now just take the part you need

Use transparency on all sides except where you want the triangle.

Top

Left

Right

Bottom

For tooltip tails, you just need to position an empty tail element relative to your tooltip element, and use negative coordinates to move the visible part of the border adjacent to the tooltip. One common trick is to generate the tail using a pseudo element in the CSS. This snippet is for tooltips appearing above an element. It generates an empty element after (below) the tooltip with a red tail that points downward toward the element.

.above:after {
 position: absolute;
 display: block;
 border: 10px solid;
 border-color: red transparent transparent;
 left: 16px;
 bottom: -20px;
 content: '';
}

We are doing something like this in Orion, but the down side is that you end up with a flat tooltip (because only one element, the pseudo-element, renders the tail). For tooltips and tails with borders or shadows, you'll probably want to place multiple tail elements with different triangle effects. There are great examples out there so I won't cover that here. I just wanted to show the sequence of pictures that I wish I'd seen first.

2 comments:

  1. Yeah - read your tweet and followed the link but didn't get how this works. Those images make it really easy to understand this trick ;-)

    What would be really nice in CSS would be if one can define could define a clip-shape (e.g. an SVG-Path)on an element ;-)

    ReplyDelete
  2. Hi, Tom...glad to hear I'm not the only one who didn't get it right away!

    If you are wanting to play with other shapes, there is a "classic" here... http://tantek.com/CSS/Examples/polygons.html

    I agree it would be cool to clip an element without resorting to border tricks!

    ReplyDelete