A CSS tooltip is a small popup callout box that displays helpful text context when a user hovers over or focuses on an element on a web page.
Tooltips can be created using position: relative, position: absolute, and data attributes (data-tooltip):
/* Relative Parent Container */
.tooltip {
position: relative;
cursor: pointer;
}
/* Hidden Absolute Tooltip Box */
.tooltip::after {
content: attr(data-tooltip);
position: absolute;
bottom: 125%;
left: 50%;
transform: translateX(-50%);
background-color: #1e293b;
color: #f8fafc;
padding: 6px 10px;
border-radius: 4px;
font-size: 0.85rem;
white-space: nowrap;
opacity: 0;
visibility: hidden;
transition: opacity 0.2s ease;
}
/* Reveal Tooltip on Hover */
.tooltip:hover::after {
opacity: 1;
visibility: visible;
}
Key steps:
data-tooltip="Hint text".attr(data-tooltip): Access data attribute text inside ::after pseudo-element content.left: 50%; transform: translateX(-50%);.flowchart TD
A["Hover over .tooltip element"] --> B["CSS: .tooltip:hover::after"]
B --> C["Toggles opacity: 0 -> opacity: 1"]
C --> D["Displays Tooltip Callout Box Above Element"]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS Tooltip Demonstration</title>
<style>
.tooltip-container {
position: relative;
display: inline-block;
}
.tooltip-container::after {
content: attr(data-hint);
position: absolute;
bottom: 130%;
left: 50%;
transform: translateX(-50%);
background-color: #334155;
color: #38bdf8;
padding: 6px 12px;
border-radius: 4px;
font-size: 0.85rem;
white-space: nowrap;
opacity: 0;
pointer-events: none;
transition: opacity 0.2s ease;
box-shadow: 0 4px 6px -1px rgba(0,0,0,0.4);
}
.tooltip-container:hover::after {
opacity: 1;
}
</style>
</head>
<body style="background-color: #0f172a; color: #f8fafc; font-family: system-ui, sans-serif; padding: 3rem;">
<h2>Pure CSS Tooltip Example</h2>
<span class="tooltip-container" data-hint="Copied to clipboard!" style="color: #38bdf8; border-bottom: 1px dashed #38bdf8; cursor: pointer;">
Hover over this text for hint
</span>
</body>
</html>
attr(data-tooltip) in CSS pseudo-elements: Avoid duplicating HTML elements for simple tooltips.pointer-events: none on tooltip boxes: Prevents tooltips from interfering with mouse cursor clicks on underlying elements.white-space: nowrap: Prevents short tooltip hint strings from wrapping onto multiple lines.Create a CSS pseudo-element .hint::after that reads text from content: attr(data-hint);!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.