Search code examples
htmlcsshovericonsvisual-web-developer

How to use a CSS class with an icon class in an <a> tag


I want to use a GitHub icon which should show some text when hovered over. But using a CSS class with an icon class is showing no progress. Here is the code for reference:

/* Tooltip container */

.tooltip {
  position: relative;
  display: inline-block;
  border-bottom: 1px dotted black;
  /* If you want dots under the hoverable text */
}


/* Tooltip text */

.tooltip .tooltiptext {
  visibility: hidden;
  width: 120px;
  background-color: black;
  color: #fff;
  text-align: center;
  padding: 5px 0;
  border-radius: 6px;
  /* Position the tooltip text - see examples below! */
  position: absolute;
  z-index: 1;
}


/* Show the tooltip text when you mouse over the tooltip container */

.tooltip:hover .tooltiptext {
  visibility: visible;
}
<a class="tooltip fab fa-github" style="font-size: 2em;" href='https://github.com/rohitthapliyal2000'> </a> <span class="tooltiptext">Hovered text</span>


Solution

  • If you don't want to change your markup, you could use the adjacent sibling combinator (+) in your selectors - see demo below:

    .tooltip {
      position: relative;
      display: inline-block;
      border-bottom: 1px dotted black;
      text-decoration: none; /* remove anchor underline */
    }
    
    .tooltip + .tooltiptext { /* <- note the + combinator */
      visibility: hidden;
      width: 120px;
      background-color: black;
      color: #fff;
      text-align: center;
      padding: 5px 0;
      border-radius: 6px;
      position: absolute;
      z-index: 1;
    }
    .tooltip:hover + .tooltiptext { /* <- note the + combinator */
      visibility: visible;
    }
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css">
    
    <a class="tooltip fab fa-github" style="font-size: 2em;" href='https://github.com/rohitthapliyal2000'></a>
    <span class="tooltiptext">Hovered text</span>