DEV Community

Cover image for CSS Only Tooltips Alternative
Chris Bongers
Chris Bongers

Posted on • Originally published at daily-dev-tips.com

CSS Only Tooltips Alternative

The other day we made some CSS only tooltips. And the cool part about being a developer is there are always different ways to do it. I got some feedback that the data-attribute was also a nice alternative way, so I decided to rebuild my ones.

And it is indeed a neet way of doing so. It's cleaner code, and with this one, we don't have to define a fixed width.

HTML Structure

The HTML Structure only changes slightly from our previous example.

<div class="skills">
  <div class="skills-item" data-tooltip="HTML5">
    <!-- Content -->
  </div>
  <div class="skills-item" data-tooltip="CSS3">
    <!-- Content -->
  </div>
  <div class="skills-item" data-tooltip="JavaScript">
    <!-- Content -->
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode

So basicly we removed our span and placed our tooltip content inside the data-tooltip attribute we created.

CSS Tooltip Alternative

As for our CSS we are using the tooltip attribute selector as such:

.skills-item[data-tooltip] {
  position: relative;
}
Enter fullscreen mode Exit fullscreen mode

Then we will add our actual tooltip element the box and set the content to be whatever is in our data-tooltip

.skills-item[data-tooltip]:after {
  transition: opacity 0.3s;
  opacity: 0;
  position: absolute;
  content: attr(data-tooltip);
  bottom: 100%;
  background-color: #555;
  padding: 5px 0;
  border-radius: 6px;
  color: #fff;
  padding: 8px;
  width: auto;
  right: 50%;
  transform: translateX(50%);
}
Enter fullscreen mode Exit fullscreen mode

We use the same styling, but position it slightly different by offsetting it after placing it to the right.

Now we also want to have that little arrow at the bottom and will leverage the bottom pseudo-element.

.skills-item[data-tooltip]:before {
  transition: opacity 0.3s;
  opacity: 0;
  content: '';
  position: absolute;
  border-width: 5px;
  border-style: solid;
  border-color: #555 transparent transparent transparent;
  right: 50%;
  transform: translateX(50%);
  margin-top: -10px;
}
Enter fullscreen mode Exit fullscreen mode

Awesome!

Now all that's left is showing it once we hover! Remember we have to show two elements now the before and after.

.skills-item[data-tooltip]:hover:after {
  opacity: 1;
}
.skills-item[data-tooltip]:hover:before {
  opacity: 1;
}
Enter fullscreen mode Exit fullscreen mode

There you go, an alternative way of showing a tooltip.

View this on Codepen.

Browser Support

The browser support for this function mainly depends on the attribute selector, and that's pretty well supported!

Attribute Selector support

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Top comments (0)