Search code examples
cssruby-on-railsrandombackgroundselected

Random background picture CSS | RAILS


html{ 
    background: url(/assets/flower.jpg) no-repeat center center fixed; 
    -webkit-background-size: cover;   
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

How can I make this code randomly choose from a selected number of pictures as background. I am using Rails 3, so have that in mind, if that will simplify the process of making this work. THANKS! :D


Solution

  • In your view file where you would like to display the background image, add this line

    <style type="text/css">
      html {
        background: url(<%= randomized_background_image %>) no-repeat center center fixed; 
      }
    </style>
    

    Now in your application_helper

    def randomized_background_image
      images = ["assets/foo.jpg", "assets/random.jpg", "assets/super_random"]
      images[rand(images.size)]
    end