DEV Community

Michael Burrows
Michael Burrows

Posted on • Originally published at w3collective.com

Setup a HTML tooltip on hover using CSS

Tooltips are little boxes containing helpful text that appear when you hover over certain elements in a web page. They’re a useful UI component for providing additional information to users without having to clutter the interface. In this tutorial we’ll be creating a simple tooltip using HTML & CSS with no JavaScript required.

Let get started with the HTML markup:

<p>Example CSS Tooltip <span data-tooltip="Tooltips are used to provide information about an element on a web page.">i</span></p>
Enter fullscreen mode Exit fullscreen mode

The tooltip will appear when we hover over the <span> element displaying the text from the data attribute. Alternatively you could apply the data attribute to a hyperlink or button and the tooltip will function the same way.

Now for the CSS starting with the tooltips trigger element:

[data-tooltip] {
  position: relative;
  cursor: pointer;
  background: black;
  color: white;
  font-size: 12px;
  border-radius: 1em;
  padding: 0 0.5em;
}
Enter fullscreen mode Exit fullscreen mode

As we’re using a data attribute we can use the CSS [attribute] selector which selects all elements with a specified attribute (data-tooltip). The actual tooltip that appears on hover will be constructed using :before and :after pseudo elements:

[data-tooltip]:before {
  content: attr(data-tooltip);
  position: absolute;
  opacity: 0; 
  width: 150px;
  transform:translateX(-50%);
  bottom: 25px;
  padding: 0.5em;
  background-color: black;
  border-radius: 0.25em;
  color: white;
  text-align: center;
  transition:0.2s;
}
Enter fullscreen mode Exit fullscreen mode

Next we’ll a small arrow shape so the tooltip looks like a speech bubble:

[data-tooltip]:after {
  content: "";
  position: absolute;
  opacity: 0; 
  bottom: 15px;  
  margin-left: -5px; 
  border: 5px solid black;
  border-color: black transparent transparent transparent;
  transition:0.2s;
}
Code language: CSS (css)
Finally we need to set the opacity to be visible when the tooltip element is hovered:

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

That’s all for this tutorial, we’ve just created a animated tooltip using only HTML and CSS. The only drawback when creating tooltips using this method is data attributes don’t support hyperlinks so these tooltips are unable to contain links and are purely text only.

Top comments (0)