Random CSS Background Image | 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 to make this code randomly selected from a selected number of images as background. I'm using Rails 3, so keep that in mind if it makes it easier to get the job done. THANKS !: D

+3


source to share


3 answers


In your view file where you want to display 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 application_helper

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

      

+7


source


The easiest way is to create actions with a redirect to a random image, the browser will follow the redirect.

App / controller / background_controller.rb

class BackgroundController < ApplicationController
  def image
    redirect_to "/assets/images/background_#{rand(10)}.jpg"
  end
end

      

This will randomly redirect to the background image between background_0.jpg

andbackground_9.jpg

config / routes.rb

Something::Application.routes.draw do
  get '/random_background.jpg', to: 'background#image'
end

      

CSS

html{ 
  background: url(/random_background.jpg) no-repeat center center fixed;
}

      




Some more advanced would be able to do something like this in middleware, so it won't need the entire rails package for such a request.

app / intermediate / random_background_middleware.rb

class RandomBackgroundMiddleware
  def initialize(app, count = 10)
    @app = app
    @count = count
  end

  def call(env)
    if env["PATH_INFO"] == "/random_background.jpg"
      [302, {"Location" => "/assets/images/background_#{rand(@count)}.jpg")}, '']
    else
      @app.call(env)
    end
  end
end

      

config/application.rb

config.middleware.insert_before 0, "RandomBackgroundMiddlware"

      

insert_before 0

used to place it at the top of the intermediate chain




Or even better would be something like this in your web server configuration. But I don't understand how to do it.

+8


source


I did it by creating a random class name in the view like this:

<div class="homepage-banner-<%= rand(1..10) %>">

      

Then I just added some images to my CSS like this:

.homepage-banner-1
  background-image: image-url('homepage/homepage-feature-1.jpg')

.homepage-banner-2
  background-image: image-url('homepage/homepage-feature-2.jpg')

.homepage-banner-3
  background-image: image-url('homepage/homepage-feature-3.jpg')

etc.

      

Not sure if this is the best way, but it is very simple.

+3


source







All Articles