tags:

views:

571

answers:

2

I need an on hover semi-transparent div which includes some text to appear over the top of a thumbnail image? Is it possible to do this without using JS and use just CSS?

+4  A: 

You can try something like this:

<style type="text/css">
.thumb {position:relative;width:200px;height:20px;}
.thumb:hover .overlay {opacity:0.5;}
.overlay {position:absolute;top:0;left:0;width:200px;height:20px;background:#fff;opacity:0;}
</style>
<div class="thumb">
    <div class="overlay"></div>
    <img src="image.gif" />
</div>
easwee
Great, thanks for this works great! What about IE? I take it won't work there? :-(
Rob Such
Use filter opacity: http://doctyper.com/archives/200703/cross-browser-opacity/
D_N
You actually don't really need to use conditional comments for it since the browser will simply ignore the css rule it doesn't understand. A selector like this http://snipplr.com/view/10094/crossbrowser-opacity/ should do the trick.
easwee
A: 

Depending on what you're doing with the thumbnail, you could set the background of the DIV as the image, include the text, and use CSS to toggle the visibility from transparent to solid on hover.

This'd only work cleanly if you have a known-size thumbnail (because it's hard to autosize a div to the size of its background image), but it'll make for a simple solution in your html:

<div class="thumb" style="background-image: url(thumb.jpg);">
     <p>mouseover text</p>
</div>

The important css would be something like this...

div.thumb p { visibility: hidden; }
div.thumb:hover p { visibility: visible; }

Not sure from your question whether the whole div is supposed to be transparent or just the text, but you can apply the relevant CSS at either level.

Dan Puzey
All fine as far as displaying it goes - but you are not caring about semantics here. Using the img tag you can specifly other useful attributes like the alt text, width and height (which will also render faster) and any other behaviours you may need. You are also cutting away users with screen readers since they won't know what exactly they are looking at.
easwee
That's why I said "depending on what you're doing," though admittedly I didn't make myself clear enough. My guess from context that the text is more important than the image, in which case this may be a reasonable approach.
Dan Puzey