How to Display a Tooltip on Mouse Hover Using CSS
Showcase
mouse hover
If you hover the mouse over ‘mouse hover’, a tooltip appears.
Code
HTML
<div class="container" tooltip="This is tooltip">mouse hover</div>
class="container"
: Acts as the container wrapping the element that displays the tooltip.tooltip
: Specifies the content to be displayed in the tooltip.
CSS
The following CSS is written inline as in the HTML
code for simple testing. In practice, it is preferable to place it in a separate CSS file.
<style>
.container {
position: relative;
}
.container:hover::after {
content: attr(tooltip);
background-color: rgba(0, 0, 0, 0.5);
color: white;
}
</style>
.container:hover::after
: Defines styles for the::after
pseudo-element when an element with thecontainer
class is hovered. They are called pseudo-elements because they do not have an actual content area.content: attr(tooltip)
: Displays the value of thetooltip
attribute as the tooltip.