DEV Community

Anand Roshan
Anand Roshan

Posted on

Creating Simple Tooltips with Pure CSS as a Beginner

Tooltips are a common UI element that provide additional information when users hover over an element. They are often used to clarify the purpose of buttons or icons.

In this tutorial, we will create a simple tooltip using only HTML and CSS. While tooltips can also be created using JavaScript, this tutorial focuses on a pure CSS approach to keep things simple for beginners.

HTML Structure

Let's start by looking at the HTML structure we'll use to create our tooltip:

<div class="tooltip">
    <label class="text">Tooltip</label>
    <button>Hover Me</button>
</div>
Enter fullscreen mode Exit fullscreen mode

We have a <div> element with the class "tooltip" containing two child elements:

  • A <label> with the class "text" (this will be our tooltip content)

  • A<button> element (the element we'll hover over to trigger the tooltip).

CSS Styling

Main .tooltip should have a position property.

.tooltip {
    position: relative;
}
Enter fullscreen mode Exit fullscreen mode

This is the styling for the actual tooltip that appears after hovering. If you want, you can change the background-color property or add a border, box-shadow, etc.

.tooltip .text {
    visibility: hidden;
    background-color: #000000;
    color: #ffffff;
    text-align: center;
    box-sizing: border-box;
    padding: 5px 5px;
    border-radius: 5px;
    position: absolute;
    z-index: 1;
    top: -40px;
    font-size: 12px;
    width: max-content;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
}
Enter fullscreen mode Exit fullscreen mode

Then we use the ::after psuedo selector in CSS to create an arrow for the tooltip. Both ::after and :after will work.

.tooltip .text::after {
    content: "";
    display: block;
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 10px solid #000000;
    position: absolute;
    bottom: -10px;
}
Enter fullscreen mode Exit fullscreen mode

Finally, we make the text visible when the .tooltip is hovered over use :hover psuedo-class.

.tooltip:hover .text {
    visibility: visible;
}
Enter fullscreen mode Exit fullscreen mode

And there you have it! We've created a simple tooltip using pure CSS and HTML.

Certainly, here's an improved and more professional version of the statement:

We can enhance the functionality of this tooltip using JavaScript in several ways, such as automatically detecting screen edges and adjusting the tooltip's position accordingly.

We can optimize the HTML structure by defining the tooltip text within the HTML element as a data attribute, eliminating the need for additional HTML elements and so on.

I'll post it as a separate article.

Also, check out my CSS Tooltip Generator,ย which will be helpful if you are a beginner.

Top comments (0)