My new best CSS friend – content: attr(data);

How to use the data attribute in CSS content

June 27th 2013 - Code


I have been experimenting with the CSS content property quite a bit lately. What I discovered is you can populate it with the HTML data attribute.

For example say we wanted an item to have a tooltip. We would write out the HTML like this:

   This is my link

Now in the CSS all we have to do is:

 #my-link {
    position: relative;

  #my-link:before {
     diplay: block;
     content: "";
     position: absolute;
     bottom: -40px;
     opacity: 0.6;
     color: #fff;

  #my-link:hover:before {
    content: attr(data-tooltip);
    padding: 2px;
    border-radius: 5px;
    background: #000;

Now we have a working tool tip without JavaScript. Of course we could style it some more to making even more tooltipy but you get the idea. Check out the demo.