Display tooltip to div with pure css and javascript in html example

Tooltip in HTML is important information to be displayed in an element while mouse over an element. An element can be a div, button, or input control.

This tutorial explains adding a tooltip to the div element with examples.

There are multiple ways we can add a tooltip to the Div element in HTML pages.

  • Pure css
  • Pure Javascript

How to add a tooltip to the div element with pure CSS

<div class="tooltipContainer">
  <span class="tooltip">Please enter name</span>
  <input type="text" name="name" />

CSS code:

.tooltipContainer {
  position: absolute;
  display: inline-block;
  cursor: pointer;

.tooltipContainer .tooltip {
  visibility: hidden;
  width: 130px;
  background-color: blue;
  color: #fff;
  text-align: left;
  border-radius: 6px;
  padding: 5px 10px;
  position: absolute;
  z-index: 1;
  bottom: 160%;
  left: 100%;
  margin-left: -140px;
  opacity: 0;
  transition: opacity 1s;

.tooltipContainer .tooltip::after {
  content: "";
  position: absolute;
  top: 100%;
  left: 50%;
  margin-left: -15px;
  border-width: 15px;
  border-style: solid;
  border-color: #555 transparent transparent transparent;

.tooltipContainer:hover .tooltip {
  visibility: visible;
  opacity: 1;

In the above example, No javascript is added.

Display Tooltip with pure javascript

In this example, Html mouse events like onmouseover and onmouseout are being used for tooltip display.

onmouseover event is called when the element gets focused on the mouse.

onmouseout event is called when an element lost focus.

create a tooltip text with custom styles, this will not be shown by default. When the mouse hovers it, a tooltip is shown using the element.display.style=block else display=none as shown below

Codepen tooltip pure CSS and javascript example You can check the complete example code for adding a tooltip with pure CSS and javascript

See the Pen