Daniel Koczuła
Daniel Koczuła

Reputation: 1034

Move background image up and down

I've got a div with background image. How to do this: when you hover on that div, the background image moves 5px up and then 5 pixel down? For example fast up, and slow down.

My code:

CSS

<style>
.place {
background:url(../img/place.png) no-repeat 6px 50%;
}
</style>

HTML

 <div class="place">
    123 Something Street<br/>
    UB5 212 Liverpool
    </div>

How to do this with transition? Or jquery?

Upvotes: 1

Views: 7742

Answers (4)

Ayyappan Sekar
Ayyappan Sekar

Reputation: 11475

All you need to add is background-position style to your div background and do some little jQuery stuff:

  1. add to css:

    background-position: 10px 10px;

  2. and to ready of jQuery :

    $('.place').hover(function(){ $('.place').css('background-position', '10px 5px'); setTimeout(function(){ $('.place').css('background-position', '10px 10px');
    }, 2000); });

Here is the working example

Upvotes: 0

Atif
Atif

Reputation: 10880

Using CSS3

.place {
    background:url(http://lorempixel.com/20/20/) no-repeat;
}

div.place:hover {
    animation:myanim 0.5s;
    -webkit-animation:myanim 0.5s;
    /* Safari and Chrome */
}

@keyframes myanim {
    0% {
        background-position:0 0;
    }
    50% {
        background-position:20px 0;
    }
    100% {
        background-position:0 0;
    }
}

@-webkit-keyframes myanim
/* Safari and Chrome */
 {
    0% {
        background-position:0 0;
    }
    50% {
        background-position:20px 0;
    }
    100% {
        background-position:0 0;
    }
}

Upvotes: 5

RDK
RDK

Reputation: 4560

Also you can try CSS3:

   transition: background-position 1s ease;
   -moz-transition: background-position 1s ease; /* Firefox */
   -webkit-transition: background-position 1s ease; /* Safari and Chrome */

Upvotes: 1

YD1m
YD1m

Reputation: 5895

Use .animate() for background-position property:

    $('div.place').on('hover', function() {
      $(this).animate({
         'background-position-y': '15px'
      }, 500, 'linear');
   });

Upvotes: 1

Related Questions