CSS simple tooltip by Chris Bracco

Posted on September 15th, 2019

Below is a CSS simple tooltip with a link or a button created by Chris Bracco. To see how it works, just click on the button Run Pen:

How to create a CSS simple tooltip

Step 1: Add Html

<h1>CSS Simple Tooltip</h1>
<div class="demo">
  <p>
    <a href="#" data-tooltip="I’m the tooltip text.">
      I’m a link with a tooltip.
    </a>
  </p>
  <p>
    <button data-tooltip="I’m the tooltip text.">
      I’m a button with a tooltip
    </button>
  </p>
</div>

Step 2: Add CSS

/**
 * Demo styles
 * Not needed for tooltips to work
 */

/* `border-box`... ALL THE THINGS! */
html {
  box-sizing: border-box;
}

*,
*:before,
*:after {
  box-sizing: inherit;
}

body {
  margin: 64px auto;
  text-align: center;
  font-size: 100%;
  max-width: 640px;
  width: 94%;
}

a:hover {
  text-decoration: none;
}

header,
.demo,
.demo p {
  margin: 4em 0;
  text-align: center;
}

/**
 * Tooltip Styles
 */

/* Add this attribute to the element that needs a tooltip */
[data-tooltip] {
  position: relative;
  z-index: 2;
  cursor: pointer;
}

/* Hide the tooltip content by default */
[data-tooltip]:before,
[data-tooltip]:after {
  visibility: hidden;
  -ms-filter: 'progid:DXImageTransform.Microsoft.Alpha(Opacity=0)';
  filter: progid: DXImageTransform.Microsoft.Alpha(Opacity=0);
  opacity: 0;
  pointer-events: none;
}

/* Position tooltip above the element */
[data-tooltip]:before {
  position: absolute;
  bottom: 150%;
  left: 50%;
  margin-bottom: 5px;
  margin-left: -80px;
  padding: 7px;
  width: 160px;
  -webkit-border-radius: 3px;
  -moz-border-radius: 3px;
  border-radius: 3px;
  background-color: #000;
  background-color: hsla(0, 0%, 20%, 0.9);
  color: #fff;
  content: attr(data-tooltip);
  text-align: center;
  font-size: 14px;
  line-height: 1.2;
}

/* Triangle hack to make tooltip look like a speech bubble */
[data-tooltip]:after {
  position: absolute;
  bottom: 150%;
  left: 50%;
  margin-left: -5px;
  width: 0;
  border-top: 5px solid #000;
  border-top: 5px solid hsla(0, 0%, 20%, 0.9);
  border-right: 5px solid transparent;
  border-left: 5px solid transparent;
  content: ' ';
  font-size: 0;
  line-height: 0;
}

/* Show tooltip content on hover */
[data-tooltip]:hover:before,
[data-tooltip]:hover:after {
  visibility: visible;
  -ms-filter: 'progid:DXImageTransform.Microsoft.Alpha(Opacity=100)';
  filter: progid: DXImageTransform.Microsoft.Alpha(Opacity=100);
  opacity: 1;
}