CSS HTML

How to make a tooltip with pure CSS

January 24, 2022

How to make a tooltip with pure CSS

In this article we will learn how to create a tooltip with pure CSS. Tooltip is a legend/tip that stands over another element explaining its function.

In this article we will learn how to create a tooltip with pure CSS cover

Hey you  programmer, okay? Let’s learn something new!

Before showing you the code, let’s  understand what a tooltip is

This element would be an aid to some other element, as if it were a tip or instruction.

That transmits a message as soon as the user hovers over a particular element

That said, you can create this action and element with just HTML and CSS

So, take a look at the following example:

<div class="tooltip">
 Hover here
 <span>This is your tip<span>
</div>

We created the HTML framework, where the div would be the element that appears on the page.

And the span or tooltip, which will appear later

See that we need to add CSS:

body {
 margin: 100px;
}

.tooltip {
 cursor: pointer;
 display: block;
 position: relative;
 width: 100px;
}

div.tooltip span {
 position: absolute;
 text-align: center;
 visibility: hidden;
 background-color: #000;
 color: #FFF;
 padding: 5px 10px;
}

div.tooltip span:after {
 content: '';
 position: absolute;
 bottom: 100%;
 left: 50%;
 margin-left: -8px;
 width: 0; height: 0;
 border-bottom: 8px solid #000;
 border-right: 8px solid transparent;
 border-left: 8px solid transparent;
}

div:hover.tooltip span {
 visibility: visible;
 opacity: 0.9;
 top: 30px;
 left: 0;
 z-index: 999;
}

A lot of code, but for a good reason, before I explain everything, let’s see the result in the browser:

Now that we’ve seen that the code works, let’s go through the explanations.

First block of code, I inserted a margin in the body just to space the element from the edges

When styling the .tooltip element, I left it relative to the tooltip to be positioned absolutely relative to this element

In addition to the cursor pointer, for the mouse pointer icon to change to the little hand

Then the span style was created, which is the tooltip, to make it black with white letters and hide it with visibility: hidden

The after effect of  the span is to make a triangle with CSS, as tooltips usually have these triangles

And finally we create a hover in the parent div so that the tooltip can appear as soon as the parent element has the mouse event passing through it. Cool, isn’t that so? 😀

Conclusion

In this article we learned how to create a tooltip with pure CSS and HTML

We create an element that serves as a base and then the tooltip, which is hidden

As soon as the client hovers over the parent element, the tooltip is revealed

Which is the default behavior of this resource

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x