Create tooltips with CSS.
A tooltip is often used to specify extra information about something when the user moves the mouse pointer over an element:
HTML: Use a container element (like <div>
) and add the tooltip
class to it. When the user mouses over this <div>
, it will show the tooltip text.
The tooltip text is placed inside an inline element (like <span>
) with class="tooltiptext"
.
CSS: The tooltip
class uses position: relative;
, which is needed to position the tooltip text (position: absolute;
). Note: See examples below on how to position the tooltip.
The tooltiptext
class holds the actual tooltip text. It is hidden by default and becomes visible on hover. We have also added some basic styles to it: width: 120px;
, black background color, white text color, centered text, and padding: 5px 0;
.
The CSS border-radius
property is used to add rounded corners to the tooltip text.
The :hover
selector is used to show the tooltip text when the user moves the mouse over the element with class="tooltip"
.
In this example, the tooltip is placed to the right (left: 105%
) of the “hoverable” text (<div>
).
Also note that top: -5px;
is used to place it in the middle of its container element. We use the number 5 because the tooltip text has a top and bottom padding of 5px.
If you increase its padding, also increase the value of the top
property to ensure that it stays centered (if this is something you want).
The same applies if you want the tooltip placed to the left.
If you prefer the tooltip to be displayed above or below the hoverable text, refer to the examples below. We apply a margin-left
value of -60px
to align the tooltip in the center.
This value is half the tooltip's width (120 divided by 2 equals 60).
To create an arrow that should appear from a specific side of the tooltip, add "empty" content after tooltip, with the pseudo-element class ::after together with the content property. The arrow itself is created using borders. This will make the tooltip look like a speech bubble.
This example demonstrates how to add an arrow to the bottom of the tooltip:
If you want to fade in the tooltip text when it is about to be visible, you can use the CSS transition property together with the opacity property, and go from being completely invisible to 100% visible, in a number of specified seconds (1 second in our example):