Logo - Albert Walicki
HTML

How to create a tooltip in HTML and CSS?

A short tutorial on creating an HTML and CSS tooltip without a single line of javascript. All you need to know is data-atributes

HTML native tooltip

To create native HTML tooltip all you need is to add title to your HTML like this:

<div title="Hello, I'm HTML native tooltip">
     Hover me!
</div>

CSS + HTML tooltip

HTML native tooltip has one significant disadvantage - we can't style it. Here CSS comes to the rescue! We can create a custom tooltip using data attributes and style it with CSS. Let's see the code snippet.

<div data-tooltip="Hello, I'm custom tooltip created with CSS and HTML!">
    Hover me!
</div>
/* customizable START */

body {
  min-height: 100vh;
  width: 100%;
  margin: 200px 0;
  font-family: Arial;
}


p {
  padding: 20px 0;
  font-size: 16px;
  cursor: pointer;
  position: relative;
  text-align: center;
}

/* customizable END */


[data-tooltip]:before {
    /* required code */
    content: attr(data-tooltip);
    position: absolute;
    opacity: 0;

    /* customizable */
    top:0;
    left:50%;
    transform: translateX(-50%);
    transition: 256ms all ease;
    padding: 10px 20px;
    color: #333;
    border-radius: 5px;
    box-shadow: 0px 6px 21px rgb(0 0 0 / 10%);
}

[data-tooltip]:hover:before {
    /* required code */
    opacity: 1;

    /* customizable */
    background: #fff;
    border-radius: 5px;
    border: 1px solid #ccc;
    top: -30px;
}

And here is our result of our code on codepen:


See more solutions!

CSS

How to limit text to n lines with CSS?

Sometimes, we have to trim text to limit the number of lines. There are a few ways to do it with pure CSS. Let's learn how to achieve that

Logo - Albert Walicki

Hello, I'm a frontend developer with over six years of experience, freelancer. I'm also a mentor for junior frontend developers. I wrote a book for Junior Frontend developers called Frontend Unicorn.

BlogGlassmorphismAurora UIShapes in CSSUnique css illustrations

Get in touch!

Have a question or need a project? Contact me!

© 2020-present Albert Walicki. All Rights Reserved

Policy