jorame
jorame

Reputation: 2207

Hover effect with image as background

I don't know if there is a way to accomplish this or not. I have an image

 <img src="images/thumb.png" />

These are the CSS property of that image

float:left;
border:solid 1px #dadada;
margin: 0 5px 0 5px;
padding:5px;
border-radius:4px;
-moz-transition: border 0.2s linear 0s;

Now what I want to add a hover effect, but this hover effect has an image as a background like so:

    border:solid 1px #888888;
    opacity: 0.4;
    background: url(images/video.png) no-repeat;
    opacity:0.6;
    filter:alpha(opacity=60); /* For IE8 and earlier */

My problem is that my background image in the hover effect is not showing on top of my image like I want to.

Any help will be appreciate it. thanks

Upvotes: 1

Views: 4940

Answers (2)

Francisco Santiago
Francisco Santiago

Reputation: 31

You can wrap the img element in a div, something like this:

<div class="background">
    <img src="images/thumb.png" />
</div>

Then you can apply the background image to the div element, instead of the img element on hover state.

Your css should look something like this:

img{
    float:left;
    border:solid 1px #dadada;
    margin: 0 5px 0 5px;
    padding:5px;
    border-radius:4px;
    -moz-transition: border 0.2s linear 0s;
}

img:hover{
    border:solid 1px #888888;
    opacity:0.4; /* You can remove this line*/
    opacity:0.6;
    filter:alpha(opacity=60); /* For IE8 and earlier */
}
div.background{
    background: url(images/video.png) no-repeat;
    height: /* same as your img */
} 

Upvotes: 2

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114367

Here is a simple way to do it using jQuery. All you have to do is specify hoverImg="" and the script does the rest automagically.

<img src="http://i.imgur.com/vdDQgb.jpg" hoverImg="http://i.imgur.com/Epl4db.jpg">

$('body').find('*[hoverImg]').each(function(index){
    $this = $(this)
    $this.wrap('<div>')     
    $this.parent().css('width',$this.width())  
    $this.parent().css('height',$this.width())
    $this.parent().css('background-image',"url(" + $this.attr('hoverImg')+")")
        $this.hover(function() {
            $(this).stop()
            $(this).fadeTo('',.01)    
        },function() {
            $(this).stop()
            $(this).fadeTo('',1)             
        })                    
});

Try it here: http://jsfiddle.net/Diodeus/gYyBL/

Upvotes: 0

Related Questions