This is an easy way to display a tooltip without any javascript.
We can use CSS :after and :before selector to display the box and arow for tooltip element and display tooltip content using “attr()” css attribute. as shown in below image
Example :
VIEW DEMO
- Copy below css to your stylesheet
- Add “css-tooltip” class to the element.
- Add your tooltip content in “data-tooltip” attribute eg. “data-tooltip=”This is sample tooltip”
- Done!
HTML
<!-- to add a tooltip to anchor tag use following class and attribute --> <h3>This is a <a href="" class="css-tooltip" data-tooltip="This is sample tooltip"> tooltip </a> sentance </h3> <!-- to add a tooltip to Button use following class and attribute --> <button class="css-tooltip" data-tooltip="this is sample tooltip"> Tooltip button </button>
CSS
.css-tooltip{ position: relative; } .css-tooltip:hover:after{ content:attr(data-tooltip); background:#000; padding:5px; border-radius:3px; display: inline-block; position: absolute; transform: translate(-50%,-100%); margin:0 auto; color:#FFF; min-width:100px; min-width:150px; top:-5px; left: 50%; text-align:center; } .css-tooltip:hover:before { top:-5px; left: 50%; border: solid transparent; content: " "; height: 0; width: 0; position: absolute; pointer-events: none; border-color: rgba(0, 0, 0, 0); border-top-color: #000; border-width: 5px; margin-left: -5px; transform: translate(0,0px); }
- Contetnt is displayed using “content:attr(data-tooltip);”
- To position the tooltip above element “position: absolute; and transform: translate(-50%,-100%); ” is used.