Tooltip are like flash message or info which gives a little insight about a text, image, link etc in our website. This flash message or info displayed usually occurs when we hover over that element. So in this tutorial, we would be leaning how to create a tooltip using HTML and CSS. The steps to follow are listed below:
1. Create the HTML structure
Create an HTML element that will display the tooltip when hovered.
Html
<span class="tooltip">Hover over me</span>
2. Add CSS styles for the tooltip container
Apply CSS styles to position and style the tooltip container.
Css
.tooltip {
position: relative;
display: inline-block;
cursor: pointer;
}
.tooltip::after {
content: attr(data-tooltip);
position: absolute;
bottom: 100%;
left: 50%;
transform: translateX(-50%);
padding: 8px;
background-color: #333;
color: #fff;
font-size: 14px;
white-space: nowrap;
visibility: hidden;
opacity: 0;
transition: visibility 0s, opacity 0.3s;
}
.tooltip:hover::after {
visibility: visible;
opacity: 1;
}
In this example, the .tooltip selector positions the tooltip container relative to its parent element (position: relative;) and sets it to display as an inline block element.
The .tooltip::after selector creates the tooltip content using the ::after pseudo-element.
You can also learn more about Css pseudo selectors
The content is taken from the data-tooltip attribute using the attr() function.
The tooltip is positioned at the bottom of the parent element (bottom: 100%;) and centered horizontally (left: 50%; transform: translateX(-50%);).
We added background color, text color, padding, font size, and transition effect to the tooltip
The visibility and opacity properties are initially set to hide the tooltip (visibility: hidden; opacity: 0;). When the .tooltip element is hovered, the visibility and opacity properties are changed to make the tooltip visible (visibility: visible; opacity: 1;).
3. Add the tooltip text
Set the tooltip text using the data-tooltip attribute.
Html Code
<span class="tooltip">Hover over me</span>
<br /> /* break tags to add space */
<br />
<br />
<span
class="tooltip"
data-tooltip="
Download here">Hover over me</span>
Result
![tooltip using Css](https://codeharis.com/wp-content/uploads/2023/08/image-96.png)
By following these steps, you can create a tooltip using CSS.
You can also learn how to create a modal using Html and Css
When the user hover over the element with the .tooltip class, the tooltip with the specified text will be displayed.
You can modify the CSS styles as needed to match your desired tooltip appearance.
Pingback: How to create a modal box using HTML and CSS - codeharis
Pingback: Responsive Navbar using HTML and CSS? - codeharis