CSS3 Tooltips
Jul 13, 2011 | In CSS, Tutorials |Today, I’m going to show you how to replicate something that is normally done with javascript: A tooltip. Every browser out there takes the title tag of an element and displays this, but sometimes, the default browser “tooltip” just isn’t enough. That’s the reason for this CSS snippet. If you want the “tooltip” text to be actually visible, read on.
So, we’re going to need to simple divs for some demonstration purposes.
<div title="Tooltip text for first div"></div> <div title="Tooltip text for second div"></div>
As you can see, we’re keeping the html to a minimum.
Now, we can make these divs visible.
div { height: 100px; width: 100px; background: red; float: left; margin-right: 100px; }
We have two bright red divs. If you hover over either of them, in a few seconds, your browser will display a small tooltip. As I said before, this isn’t enough. Using CSS3, we can improve this a little.
div:before{ content:attr(title); display:none; } div:hover::before{ width:200px; display:block; background:yellow; border:1px solid black; padding:8px; margin:25px 0 0 10px; } div:hover::before{ z-index:10; position:relative; }
Let me explain. On the first line, we tell the “before” content to take the div’s title. When we hover over the div, we give the “before” some styling. Lastly, we tell it to have a high z-index so that it is completely visible. This is already extremely useful, but I can think of something else we can do. How about, on your site, when a user hovers over a link, the link “href” attribute is displayed in a tooltip?
<p> Lorem ipsum dolor sit amet, I don't remember the rest, I'm too lazy to look it up, and here's a link: <a href="http://www.google.com/">Google</a>. We need some text after the link too, of course. And a little more text. And another sentence.
Add some CSS:
a:after{ content:attr(href); display:none; } a:hover::after{ width:200px; display:block; background:yellow; border:1px solid black; padding:8px; margin:25px 0 0 10px; position: absolute; } a:hover{ z-index:10; position:relative; }
If you add some nice styling, this could actually be used! Go ahead and change it to your needs, I don’t mind.