Semantic Tooltips With Pure CSS3 and HTML5
This technique is so simple that I’m really surprised nobody has come up with it before, please shoot me link if they have but I couldn’t find anything after some extensive Google action.
Currently, most people use something like this to produce a pure CSS tooltip:
Title Tooltip
(Code from CSSGlobe)
But this is another extraneous element in our HTML and won’t really make much sense to screenreaders so let’s try to produce a more semantic solution.
See it in action
The solution lies in the title attribute and CSS’s content property. We can use the attribute to dynamically insert the text with CSS. The HTML is as basic as you like:
I really like pie.
Using CSS’s content property, we then produce some content after the span like so:
.tooltip:hover:after { content: attr(title); }
HTML Dog has a list of what we can use with the content property.
Our tooltip will now show up when we hover over the span. We should probably make it a bit more visible.
.tooltip { border-bottom: 1px dotted #333; position: relative; cursor: pointer; }
.tooltip:hover:after { content: attr(title); position: absolute; white-space: nowrap; background: rgba(0, 0, 0, 0.85); padding: 3px 7px; color: #FFF; border-radius: 3px; -moz-border-radius: 3px; -webkit-border-radius: 3px; margin-left: 7px; margin-top: -3px; }
Looking to the Future
With HTML5 finally allowing custom attributes, we can make this even more semantic.
I really like pie.
You can read more about HTML5 custom attributes at JavaScript Kit.
You will then need to change the CSS to:
.tooltip:hover:after { content: attr(data-tooltip); }