Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / CSS

Tooltips in CSS

4.88/5 (7 votes)
30 Mar 2010CPOL 1  
Tooltips in CSS

Have you ever wondered how to create tooltips uisng CSS only. I had a problem before when I was tasked to create tooltips in a website and immediately I had thought of using JavaScript as that's what I am used to but to my surprise, that website blocks any JavaScripts. So the next best thing is to use CSS, to show you how to achieve that, here is a simple example. All you need is 2 images, 1 for the main background which covers the top and bottom part of the tooltip and another for the stretching background.

Here is the code to achieve it:

HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>CSS Tooltips Sample</title>

<style type="text/css">

a.myToolTip
{
	position: relative;
	color: #767676;
	font-weight: bold;
	text-decoration: none;
}
a.myToolTip span
{ 
	display: none; 
}

a.myToolTip:hover
{ 
	color: red; background:;
}
a.myToolTip:hover span.tooltip
{
	/* opacity with different browsers */
	filter: alpha(opacity:70);
	KHTMLOpacity: 0.70;
	MozOpacity: 0.70;
	opacity: 0.70;
	width:200px; /* width of the tooltip, 
                    if you adjust this you need to adjust the width of your image as well*/
	color: #000000; /* tooltip text color */
	text-align: center; /* tooltip text alignment */
	display:block;
	position:absolute;
	top:0px; left:0;
	padding: 15px 0 0 0;
}
a.myToolTip:hover span.top
{
	padding: 30px 8px 0; /* top padding */
	display: block;
	background: url(tooltip.gif) no-repeat top;
}
a.myToolTip:hover span.middle
{ 
	/* different middle bg for stretch */
	padding: 0 8px;
	display: block;
	background: url(tooltipfiller.gif) repeat bottom;
}
a.myToolTip:hover span.bottom
{
	padding: 3px 8px 10px; /* bottom padding */
	display: block;
	background: url(tooltip.gif) no-repeat bottom;
}
</style>
</head>

<body>
<div id="container">
<a href="#" class="myToolTip">
Mouse Over
<span class="tooltip">
<span class="top"></span>
<span class="middle">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
Cras sit amet velit a arcu condimentum fermentum. 
Pellentesque est sapien, sollicitudin pretium accumsan sed, mollis quis leo. 
Sed ac vehicula lacus. Nulla ac massa eu felis mollis pulvinar sit amet vel eros. 
In ultrices facilisis lorem, quis semper lorem gravida vitae.


</span><span class="bottom"></span></span></a>

</div>
</body>
</html>

And here are the images:

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)