Thu Aug 27 2020

QuickTip: Css only tool tip

Tool tips can sometimes be useful to display things like help texts and similar. This post demonstrates how to create a tool tip without any JavaScript, only using HTML and CSS.

Example - Tooltip on hover

This example uses the hover event. This does work (isj) even on touch devices, but it's a good idea to provide a fallback.
	<a href="" data-tip="This is a tooltip"> Hover over me. </a>

The html is just an anchor tag inside a div. The anchor tag has a data attribute called «tip», this is will be used as the source for the tooltip content.

First selector - «a[data-tip]»

All of the CSS rules uses attribute selectors. You don't need to use attribute selectors, but it makes it easier to target only those `a` elements that has tool-tip data attached.

a[data-tip] {
	position: relative;
	color: #00f;

This selector targets the anchor tag itself. The only required property here is position:relative, this is needed to gain a working starting position for the tooltip.

Second selector - «a[data-tip]:hover/focus::after»

a[data-tip]:focus::after {
	content: attr(data-tip);
	position: absolute;
	left: 0;
	top: 24px;
	min-width: 200px;
	border: 1px black solid;
	border-radius: 5px;
	background-color: rgba(0, 0, 0, 0.5);
	padding: 12px;
	color: white;
	font-size: 14px;
	z-index: 1;

This is where it all happens. The main thing making this work is the ::after pseudo selector. When used with the content property it will insert a pseudo element as the last child of the selected element. In this example it adds the tooltip text as a child element to the anchor tag.

  • «content: attr(data-tip)» sets the content of the tooltip to the content in the «tip» data attribute.
  • «position:absolute» and the «left/top» values sets the position of the tooltip relative to the anchor tag
  • The rest of the css is mostly styling the tooltip.

How does this example work on touch-devices?

Hover doesn't exist on touch devices. However, browsers have implemented the hover action to trigger on first tap. So, when the user taps the hover target, the hover event will trigger, on the next tap any other events (like click for links) triggers.

References and links