7

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!

Jordan H
  • 52,571
  • 37
  • 201
  • 351

2 Answers2

12

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

Delan Azabani
  • 79,602
  • 28
  • 170
  • 210
  • Thanks, this is perfect! I love that doing it this way even gives you a different rotation degree when hovering on and off the same element. – Chris Barr Feb 15 '13 at 04:05
4

I know this is old, but I've found this via Google in 2022 and there is a pseudo random way to achieve a similar effect with pure CSS.

It does take some tweaking the rotations and order of positive and negative values to match your design width, or it will generate a very visible repeating pattern.

Try it out and play with the values until you find something that matches your design.

/* setup */
section {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}
div {
  width: 100px;
  height: 100px;
  background: #E54575;
}
/* maaagic */
div { transform:rotate(5deg); }
div:nth-child(2n) { transform:rotate(-4deg); }
div:nth-child(3n) { transform:rotate(2deg); }
div:nth-child(4n) { transform:rotate(-5deg); }
div:nth-child(5n) { transform:rotate(-6deg); }
div:nth-child(6n) { transform:rotate(6deg); }
/* ... you can add or remove more rotations here... */
<section>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</section>
Tim Schoch
  • 5,764
  • 2
  • 15
  • 20