Tooltips are used all over the web, typically to give the user more information about what a button might do, or to let them know what kind of info should be entered as an input. This is nice because it allows for a minimalist UI that provides details only when they become necessary.
This solution actually works pretty similarly to the Accordion example that I showed in my last post. The tooltip is nested inside each item such that it’s sibling, the button, comes before it. This layout allows us to leverage the sibling selector to trigger the tooltip and change its opacity to 1 when the button is hovered on. Setting a transition on this attribute gives a nice fade in effect.
Although the tooltip actually sits within the
.item element, we want to separate it such that it appears to be outside – this is achieved by applying
position: relative to the
.item and then applying
position: absolute to the tooltip itself and positioning it into the correct place. In this example I take advantage of
calc() to combine percentage and em based units. Basically what I am doing is putting it right below the button, and then moving it down an additional 2em past that. I’m a big fan of the using
calc(), and it’s nice to know that it has really good support at this point.
Since the arrow should sit on the top and middle of the tooltip,
position: absolute is once again the clearest solution, but this is a bit awkward because the tooltip itself is already set as absolutely positioned and we want the arrow to be positioned relative to that. To overcome this I nested another div called
.tooltip and set that as relative. If I wanted to, I could have nested yet another div and set that as absolute, but I used a pseudo element instead. The
:after selector is kinda built to append text to the end of an element, but this can be worked around by setting the content to an empty string and specifying the display style as block.
The last piece of the puzzle is turning the block we have positioned from a square to a triangle. So, how do you make triangles in CSS? One way is with borders … check out the demo below.
The key to this trick is the way that borders fit together – you can see that they will ‘chamfer’ such that they join on a 45 degree angle for a square. Looking at the third box, you can imagine that if all the sides of the border are transparent except one a triangle (an isosceles triangle) will appear. Likewise, you can set two sides as transparent to create right triangles.
Downsides and Summary