Modern CSS helps greatly in streamlining the drawing of tooltips: if it wasn't for flexbox layout we were still obliged to resort to tricks like a negative margin, to keep a group of elements neatly centred. But what about that little bottom triangle characterising the tooltip itself? Sometimes old solutions don't lose contemporaneity.
A Triangle from a Border
All right, with CSS a border can give shape to a triangle. But how?
A HTML element's border is not rendered by the browser as a whole, actually the border is made up of four distinct sections, each of which can have different characteristics. Moreover, in the corners, where two sections of the border meet, the rendering is all but continuous.
If you draw a border enough thick, and you give each section a different colour, you will see what I'm talking about: four isosceles trapezoids composing the border.
You may get the above result with a snippet of code like this:
Have you glimpsed the triangle? Not jet? So try to make the HTML element collapse on itself by removing its content and
padding, or alternately, setting its
padding to zero.
Result: four triangles at our disposal.
The good news is that this technique is applicable to pseudo-elements too!
The Starting Point
After this short premise, we can start coding!
As it is usually a good practice to keep the markup minimal, we are going to draw everything from three
<span>. Why not using the
<div> element? Because the
span element lets us include our soon-to-be tooltip in either inline and block elements without the risk of invalidating the markup.
To start with, we write our first lines of CSS to shape a disk, with a question mark in the middle, out of the
This is the rendering of the code just written:
Shaping the Tooltip
The actual tooltip is composed of two parts:
- an absolutely positioned rectangle with a fixed width shaped out of the
- an absolutely positioned triangle born out of the
.tooltip::beforepseudo-element by using the technique described at the beginning of the post.
.tooltip is absolutely positioned, the wrapper element will collapse to the size of the
.help-point element. This way, when we apply some flexbox rules to centre the tooltip relative to the wrapper, the tooltip will be automatically centred relative to the
.help-point element, too.
Here is the code:
The Whole Cascade
Obviously there are variants to the design proposed in this post, but the basic concepts will keep being valid.
Just as a summary, the markup we started from is the following:
And the tidied-up cascade of CSS rules used to style it is the one below — a good starting point to give life to something creative: