Lesson 66 +10 XP

Tooltips

Tooltips

A small info bubble that appears next to an element. Pure HTML + CSS!

The base structure

<div class="tooltip">
  Hover over me
  <span class="tooltiptext">Useful info</span>
</div>

The CSS

.tooltip {
  position: relative;
}
.tooltip .tooltiptext {
  position: absolute;
  bottom: 100%;                     /* above the element */
  left: 50%;
  transform: translateX(-50%);
  visibility: hidden;               /* hidden by default */
  background-color: #555;
  color: #fff;
  border-radius: 6px;
  padding: 5px 10px;
  white-space: nowrap;
}
.tooltip:hover .tooltiptext {
  visibility: visible;
}

The arrow

Add a little arrow through a bordered ::after:

.tooltip .tooltiptext::after {
  content: "";
  position: absolute;
  top: 100%;                        /* at the bottom edge */
  left: 50%;
  margin-left: -5px;
  border-width: 5px;
  border-style: solid;
  border-color: #555 transparent transparent transparent;
}

Positioning variants

  • top: 100% puts it BELOW.
  • Right: left: 100%; top: 50%, then translateY(-50%).

Fade in

.tooltip .tooltiptext {
  opacity: 0;
  transition: opacity 0.3s;
}
.tooltip:hover .tooltiptext {
  opacity: 1;
}

Accessibility note

A pure-CSS tooltip relies on hover. For important info, prefer built-in HTML attributes like title or real focusable elements.

TL;DR

  • Marker: wrapper position: relative, bubble position: absolute.
  • Hide with visibility: hidden + opacity: 0, show on :hover.
  • ::after triangles make the little arrow.
  • Center with left: 50% + translateX(-50%).
  • Keep tooltips decorative: put critical text on the page too.