Skip to content

Instantly share code, notes, and snippets.

@mattmccray
Last active September 1, 2024 20:19
Show Gist options
  • Save mattmccray/c9fb3c7aadb8a2f60ae294d874de3ab5 to your computer and use it in GitHub Desktop.
Save mattmccray/c9fb3c7aadb8a2f60ae294d874de3ab5 to your computer and use it in GitHub Desktop.
CSS-Only tooltip via data attributes.
@media (hover: hover) {
/* Enable CSS tooltips in a parent element */
.enable-css-tooltips {
[data-tooltip] {
position: relative !important;
}
[data-tooltip]:hover::after,
[data-tooltip]:focus::after {
contain: paint;
content: attr(data-tooltip);
position: absolute;
width: max-content;
pointer-events: none;
background-color: #111;
color: #fff;
padding: 0.25rem 0.75rem;
border: 1px solid #fff5;
border-radius: 0.3rem;
box-shadow: 0 0 8px rgba(0, 0, 0, 0.5);
font-size: 0.9rem;
font-weight: 200;
z-index: 9999;
opacity: 1 !important;
}
/* Positioning based on data-tooltip-pos attribute */
[data-tooltip]:not([data-tooltip-pos]):hover::after,
[data-tooltip]:not([data-tooltip-pos]):focus::after,
[data-tooltip][data-tooltip-pos="bottom"]:hover::after,
[data-tooltip][data-tooltip-pos="bottom"]:focus::after {
top: calc(100% + 0.5rem);
left: calc(100% / 2);
transform: translateX(-50%);
}
[data-tooltip][data-tooltip-pos="top"]:hover::after,
[data-tooltip][data-tooltip-pos="top"]:focus::after {
bottom: calc(100% + 0.5rem);
left: calc(100% / 2);
transform: translateX(-50%);
}
[data-tooltip][data-tooltip-pos="right"]:hover::after,
[data-tooltip][data-tooltip-pos="right"]:focus::after {
top: calc(50% - 15px);
left: calc(100% + 0.5rem);
}
[data-tooltip][data-tooltip-pos="left"]:hover::after,
[data-tooltip][data-tooltip-pos="left"]:focus::after {
right: calc(100% + 0.5rem);
top: calc(50% - 15px);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment