Create tooltip by using CSS

CSS Positioning

Ckmobile

--

In this article, we are going to create a tool tip. A tool tip composed by simply a rectangle and a triangle.

What we want to do is when the user mouse over the orange box. the tooltip with appear.

Photo by Joan Tran on Unsplash

Create orange box

At index.html, create a div with class name is

<div class="box" tooltip="This is tooltip"></div>

Create a box by using the following CSS rules.

.box{width: 50px;height: 50px;background-color: orange;position: relative;}

Create the green yellow rectangle

We create the green yellow box with position absolute, get the content from the attribute “tooltip”. Set the height to 25px and width is max-content. Set the background color as greenyellow.

.box::before{position: absolute;content: attr(tooltip);height: 25px;width:max-content;background:greenyellow;}

Create a light blue triangle

We already covered how to create a triangle with Pure CSS before.

.box::after{position:absolute;content:'';border: 20px solid  transparent;border-top-color: blue;}

Move the triangle and rectangle to make it look tooltip

First, we move both the triangle and rectangle 50% from its left edge of its nearest positioned ancestor.

Move the element 50% of its width from its current position by using transform.

If we move the element 100% of its height. It will look like this.

You will see the blue triangle is not just on top of the orange box. This is because actually there is border there.

--

--