#AD Top Online Web Development & Programming Courses | Udemy
Newsletter Screenshot

Setup a HTML tooltip on hover using CSS

Last modified April 13th 2021 | GitHub Source Code [GitHub] | #css #html

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>Code language: HTML, XML (xml)

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;
}Code language: CSS (css)

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;
  bottom: 25px;
  padding: 0.5em;
  background-color: black;
  border-radius: 0.25em;
  color: white;
  text-align: center;
}Code language: CSS (css)

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;
}Code language: CSS (css)

Finally we need to set the opacity to be visible when the tooltip element is hovered:

[data-tooltip]:hover:after {
  opacity: 1; 
}Code language: CSS (css)

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.

Related Posts

#AD Shop Web Developer T-Shirts