How do I add a tool tip to a span element?


CSS stands for Cascading style sheets. It is developed by Hakon Wium, Bert Bos, World Wide Web 17 December 1996.

CSS is a stylesheet used to specify the styling of the HTML elements present in the web page. It allows web developers to control the layout, colors, fonts, margins, padding, Height, Width, Background images, etc. The latest version of CSS is CSS3.

In this article, we are going to learn how to add a tooltip to a span element using HTML and CSS.

Creating a Tooltip

In HTML, a tooltip can be used to specify additional information about something when the user hovers over an element.

The following is the approach to create a tooltip that appears when the user moves the mouse over an element −

  • Create two <span> elements; one with class "tooltip" and another with "tooltiptext"

  • Style the "tooltip" container using the .tooltip class.

  • Style the tooltip text with the .tooltiptext class.

  • Initially, set visibility − hidden for the tooltip text.

  • Adjust the positioning with top, left, and transform.

  • Initially, set opacity: 0 for the tooltip text.

  • Add a transition effect for the tooltip text's opacity.

  • Use .tooltip:hover .tooltiptext to target the tooltip text when hovering over the .tooltip container.

  • On hover, set visibility: visible and opacity: 1 for the tooltip text.

Example

In the following example, we are adding a tooltip to an HTML span element using the above approach −

<!DOCTYPE html>
<html>
<head>
   <style>
      /* Style the tooltip */
      .tooltip {
         position: relative;
         display: inline-block;
         cursor: pointer;
         background-color: aquamarine;
      }

      /* Style the tooltip text */
      .tooltip .tooltiptext {
         visibility: hidden;
         background-color: seagreen;
         color: #fff;
         text-align: center;
         padding: 5px;
         margin-top: 10px;
         border-radius: 10px;
         position: absolute;
         z-index: 1;
         top: 50%;
         left: 125%;
         transform: translateY(-50%);
         opacity: 0;
         transition: opacity 0.3s;
      }

      /* Show the tooltip text when hovering on the span element */
      .tooltip:hover .tooltiptext {
         visibility: visible;
         opacity: 1;
      }
   </style>
</head>
<body>
   <span class="tooltip">Hover this text.
      <span class="tooltiptext">Welcome to Tutorialspoint</span>
   </span>
</body>
</html>


Updated on: 04-Aug-2023

961 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements