Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums CSS CSS3 random number

  • This topic is empty.
Viewing 7 posts - 1 through 7 (of 7 total)
  • Author
    Posts
  • #30194
    GreatPotato
    Member

    I don’t know if this is spec’d anywhere or even if it exists already but is it possible to generate a random number in CSS3?

    Would just be nice for hover effects on images, I have them rotating by a few degrees and would be nice instead if I could make it a little less robotic and a little more random…

    What I really want to do is:


    img:hover {
    -webkit-transform: rotate( random(-5, 5)deg); // generate a random number between -5 and +5
    -moz-transform: rotate( random(-5, 5)deg); // generate a random number between -5 and +5
    }

    Be nice if this was random on every hover and not just calculated on page load…

    #80337

    you cant generate a random number, but you can make it look so, like:


    img:nth-of-type(n+1):hover {
    transform: rotate(5deg);
    }
    img:hover {
    transform: rotate(-3deg);
    }
    so on

    About 5 different styles should do it

    #80257
    GreatPotato
    Member

    I was afraid js might have been the answer – I really do like to avoid it when possible (especially for something so trivial as generating a whole number between -5 and 5).

    I like the solution adrusi, I will experiment with this. Thanks!

    #80222
    TheDoc
    Member

    I’ve always used PHP for random number generation, myself.

    #80210
    Chris Coyier
    Keymaster
    #148207
    Tim Pietrusky
    Participant

    It’s now possible to use the random() SCSS function:

    .foo {
      height: random(5) + em;
      width: random(10 / 2) + 1 + em;
    }
    

    http://codepen.io/TimPietrusky/pen/CcEai

    #148219
    Tim Pietrusky
    Participant

    Yeah I know, but you can create “kind of random” animations with this function:

    $n: 16; 
    $m: 8;
    
    @keyframes random-animation {
      @for $i from 0 through $n {
        #{$i * 100% / $n} {
          @include transform(
            scale(random($n / $m) + 1.5)
            rotate(random(360) + deg)
            translate(random($n * 3 / $m) + em)
          );
        }
      }
    }
    

    The basic logic behind this is a combination of CodePen’s from Fabrice Weinberg / Ana Tudor. I added the random() function to create random keyframes.

Viewing 7 posts - 1 through 7 (of 7 total)
  • The forum ‘CSS’ is closed to new topics and replies.