How to create tooltip using scss

Posted by : on

Category : Rails

Hello There, Today I am going to show how to create tooltip using scss. It’s very easy to create tooltip without using javascript.

We can use pseudo-elements to pull in text and display it on :hover. (You could use the HTML title attribute to effectively accomplish the same solution, but you can’t style the tooltip to your liking.

Here is the example of this:

HTML

<span class="tooltip-toggle" data-tooltip="Sample text for your tooltip!">
  Label for your tooltip
</span>

SCSS

.tooltip-toggle {
  cursor: pointer;
  position: relative;

  //Tooltip text container - above element
  //You can adjust the position to make the container appear below or beside the element
  &::before {
    background-color: #000;
    border-radius: 5px;
    color: #fff;
    content: attr(data-tooltip); //This pulls in the text from the element with the tooltip
    left: -80px; //This centers the container above the element
    padding: 1rem;
    position: absolute;
    text-transform: none;
    top: -80px; //This places the container above the element that needs a tooltip
    transition: all 0.5s ease;
    width: 160px;
  }

  //Tooltip arrow
  //You can adjust the position of this to align nicely with the element that
  //needs a tooltip. You can also use `transform` to rotate it to make the
  //tooltip work below or next to the element.
  &::after {
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 5px solid #000;
    content: " ";
    font-size: 0;
    left: 9px; //This centers the arrow above the element with the tooltip
    line-height: 0;
    margin-left: -5px;
    position: absolute;
    top: -12px; //This positions the arrow at the bottom of the container
    width: 0;
  }

  //Setting up the transition
  &::before,
  &::after {
    opacity: 0;
    pointer-events: none;
  }

  //Triggering the transition
  &:hover::before,
  &:hover::after {
    opacity: 1;
    transition: all 0.75s ease;
  }
}

For more detail please visit this link.

Enjoy !!!



About Ram Laxman Yadav
Ram Laxman Yadav

Senior Software Engineering Professional | Tech Enthusiast | Mentor | Payments | Hospitality | E-Commerce, based in NCR, India

Email : info@ramlaxman.co.in

Website : https://ramlaxman.co.in