Pages

Thursday, April 28, 2011

Create tool-tips using CSS


It's real fun for me to do this without using JavaScript. Of course this would mean that extra markup is in the code. If you want clean markup you can use JavaScript to generate markup on the fly, but CSS will stay the almost the same. So here is the HTML

<html>
<head>
<tilte>Tool Tips</title>
<link type="text/css" href="tooltips.css" rel="stylesheet" />
</head>
<body>
<h1>Example</h1>
<div><a href='#' class='tooltip'>tooltip<span ">this is the awsome
tool tip! this gives me great pleasure</br></span></a>
</div>
</body>
</html>

nothing fancy about this. Content inside the <span> is used as the tool-tip. I told u , extra markup!!.

The trick in the CSS which enabled me to throw javascript away was the :hover psudo class. Postioning property is set to absolute and margin-left to a large minus value this will remove the content of the span out of the window. When mouse is hovering over the <a> element we change the property to bring them back to the screen. Daily hacks with -webkit and -moz is used to provide cross browser support.
Here is the CSS


a{
display: box;
font-size: 20;
padding: 2px 10px;
border-radius: 5px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
background-image:-moz-linear-gradient(top,green,yellow);
background: -webkit-gradient(linear,left center,right center,
from(green),to(yellow));
outline: none;
cursor: select;
text-decoration: none;
position: relative;
}

a span {
font-size: 12px;
margin-left: -999em;
position: absolute;
}

a:hover span {
border-radius: 5px 5px; -moz-border-radius: 5px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.1);
-webkit-box-shadow:5px 5px rgba(0, 0, 0, 0.1);
-moz-box-shadow: 5px 5px rgba(0, 0, 0, 0.1);
font-family:sans-serif;
color:white;
position: absolute;
left: 3em;
top: 3em;
margin-left: 0;
width: 200px;
background: #B22222;
border: 1px solid #FF8C00;
}


border-radius and box-shadow are just to make it little fancy. First CSS block is to give the <a> element a button like appearance. Left and top properties are set to slightly adjust the positioning of the <span> relative to its containing <a> element. In simple terms to move it little left and down.
Here are some other related post
http://jayaprabath.blogspot.com/2011/04/how-to-style-html-elements-to-give-them.html
http://jayaprabath.blogspot.com/2011/04/how-to-create-drop-down-menu-only-using.html
http://jayaprabath.blogspot.com/2011/04/css-background-property-reference.html
http://jayaprabath.blogspot.com/2011/04/how-to-provide-cross-browser-support.html