A cool trick I learned when starting work on my blog is that you can do tooltips entirely with CSS and attributes inside your HTML.
For the uninitiated, when I write "tooltip" I mean the little black dialog box that provides additional information about something on hover. For example, the "discord" and "twitter" buttons on this website use tooltips.
Typically, these are done in Javascript. However, thanks to the CSS attr()
function and wide support for psuedo-elements (::before
and ::after
specifically) you can fairly trivially do it all with clever CSS.
Example
Hover me to get the password to the secret base
Code time
The tooltip on that line above was created with the following HTML + CSS:
<span data-example-tooltip-for-post="The password is 12345, the same as my luggage">Hover me to get the password to the secret base</span>
<style>
[data-example-tooltip-for-post] {
/* misc styles */
font-weight:bold;
cursor:pointer;
/* require position:relative because the tooltip is position:absolute */
position:relative;
display:inline-block;
}
[data-example-tooltip-for-post]::after {
/* set up our positioning */
position:absolute;
top:50%;
left:50%;
transform:translateX(-50%);
/* use attr mixed with content to pull the attribute into the world */
content: attr(data-example-tooltip-for-post);
/* misc colors, styling */
background:#000;
color:#fff;
font-size:0.9rem;
padding:.3rem .5rem;
text-align:center;
border-radius:6px;
opacity:0;
/* set transitions so it's not instant */
transition:top .2s ease-out, opacity .2s ease-out;
}
[data-example-tooltip-for-post]:hover::after {
/* on hover, move tooltip to under the element and make it visible */
top:100%;
opacity:1;
}
</style>
In this case, we use the attribute data-example-tooltip-for-post
and pull it out using attr(data-example-tooltip-for-post)
.
You can get fancier, but these are the basics. At the time of writing, I use a similar technique for the labels on images here- no extra elements on the page, no wacky javascript. Just plain old CSS adding the labels where appropriate.