Wednesday, August 26, 2015

Fancy, Semantic tooltips with CSS only

I came across this post describing a way of allowing control over the appearance of tooltips in a semantic way that avoids too much extra markup and doesn't trip up screen readers. Really good idea.

Tooltip shown when hovering over the first really

I made a couple modifications to allow it to work with a href tags as well as non-link spans, eg:

<p>I <a href="#" data-tt="I mean really, really" class="tt">really</a> like pie.</p>

or

<p>I <span data-tt="I mean really, really" class="tt">really</span> like pie.</p>

I also spiced it up some and made it so it doesn't appear immediately, but only after hovering for a bit, and then transitions in gracefully.

Finally, since tooltips may be enclosed in a container with overflow hidden, or near the right edge of the viewport, I added some code to choose the positioning for each tooltip (lower left, lower right, upper left, or the default: upper right). When set appropriately, this ensures they can be seen.

Best of all it seems to be supported by essentially all browsers, including back to at least IE6.

Here's the CSS:

.tt {
  position: relative;
  cursor: pointer;
  outline: 0;
}
.tt:after {
  content: attr(data-tt);
  position: absolute;
  left: 1.7em;
  top: -1.7em;
  white-space: nowrap;
  color: #FFF;
  background: rgba(0, 0, 0, 0.8);
  padding: 3px 7px;
  border-radius: 3px;
  -moz-border-radius: 3px;
  -webkit-border-radius: 3px;
  margin-left: 7px;
  border: 1px solid gray;
  margin-top: -3px;
  transition-delay: 0s;
  visibility: hidden;
  opacity:0.0;
}
.tt:hover:after {
  visibility:visible;
  opacity: 1.0;
  transition-delay: .5s;
  -webkit-transition-delay: .5s;
  transition-duration: .4s;
  -webkit-transition-duration: .4s;
  transition-timing-function: ease-in;
  -webkit-transition-timing-function: ease-in;
}
.tt-lr:after {
  top: 1.7em;  
}
.tt-ll:after {
  top: 1.7em;
  left: auto;
  right: 1.7em;
}
.tt-ul:after {
  left: auto;
  right: 1.7em;
}


You can see it in action here