How to rotate an image by a random amount using CSS?

14,209

You won't need separate CSS IDs, but you could use some jQuery on the class. .each() is used instead of .css() directly here because otherwise the random angle would be generated once and used for all of the images. To rotate individally on hover:

$('.photo').hover(function() {
    var a = Math.random() * 10 - 5;
    $(this).css('transform', 'rotate(' + a + 'deg) scale(1.25)');
}, function() {
    $(this).css('transform', 'none');
});

If you want to smoothly animate these transformations, you can simply add a transform CSS property to the class:

.photo {
    transition: transform 0.25s linear;
}

Demonstration: http://jsbin.com/iqoreg/1/edit

Share:
14,209
Jordan H
Author by

Jordan H

*OS Developer

Updated on June 20, 2022

Comments

  • Jordan H
    Jordan H almost 2 years

    I have a gallery of 20 images on my web page that I would like to rotate by a random amount (-5 to 5 degrees) upon hover over each image. If possible, I'd like to use just CSS. If not, I would be open to using JavaScript or jQuery.

    My CSS is as follows:

    .photo:hover {
        z-index:1;
        transform:rotate(6deg) scale(1.25);
        -webkit-transform:rotate(6deg) scale(1.25);
        -moz-transform:rotate(6deg) scale(1.25);
        -ms-transform:rotate(6deg) scale(1.25);
    }
    

    6deg should be a random number, so every time the user hovers over an image, it rotates by a random amount between -5 and 5. Can I call a JavaScript function from within the CSS, or even a JavaScript variable? That would be better than creating 20 different CSS ids.

    How can I accomplish this? Thanks!