LAST UPDATED: AUGUST 5, 2021
How to create tooltip with CSS?
A Tooltip is a hint or info about a particular component or element which is displayed when you hover over the components or elements on the screen. The information is generally displayed in a text box.
Tooltip is displayed as long as you will hover around the element. It helps the user by providing the exact information about the links and buttons used in the webpage.
In this tutorial, we will create a tooltip using CSS.
Creating a Tooltip
The tooltip can be created using the div element. To position, the tooltip around the HTML element uses the position: absolute
property to tooltip and position: absolute
to the HTML element.
The tooltip will be hidden by default and will be shown when the mouse is over the element. To do so use the hover
class to the tooltip.
We can customize the tooltip by adding margin, background color
and so on.
Example: Creating a tooltip using CSS
Here, we added some CSS style properties to create tooltip. You can see that when hovering the mouse over the component.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML</title>
<style>
/* Tooltip container */
.container{
position: relative;
display: inline-block;
background: #F45678;
font-size: 25px;
}
/* Tooltip */
.container .tooltip {
visibility: hidden;
width: 120px;
background-color: black;
color: #fff;
text-align: center;
padding: 5px 0;
border-radius: 6px;
/* Position the tooltip */
position: absolute;
z-index: 1;
}
/* Show the tooltip text when you mouse over the tooltip container */
.container:hover .tooltip {
visibility: visible;
}
</style>
</head>
<body>
<h2> Adding tooltip to element </h2>
<div class="container">Hover over me
<span class="tooltip">Tooltip text</span>
</div>
</body>
</html>
Output
Here is the output of the above program.
Example: Positioning the tooltip
We can position the tooltip to left, right, up, and down of the element. Add top, bottom, left, and the right property to position the tooltip accordingly.
Conclusion
We can create a tooltip for an HTML element using the CSS properties. This tooltip is hidden by default and is visible only when we hover over it. We can place the tooltip at the top, bottom, left, or right of an element.