简体   繁体   中英

CSS Background image on Home Page only, in a Rails App

I am currently working on a Rails App, and am able to get an image as the background of the home page. However, I placed the code in the homepage css file, but it is being applied to the application css file also. This is resulting in the image being the background for all pages in the app.

In a Rails 3.1+ app, how do I get the background image to only appear on the homepage?

I have tried to move the background image css block to a different css file, but it still applied across all pages.

Declare styles inline for the page you want, if you declare in CSS file and you link those files in several documents than obviously it will take the background image for the respective element

Suppose it is like index.html

<style>
body {
   background-image: url('#');
}
</style>

Or simply declare a class and apply on that particular page

.unique { /* In Your CSS File */
   background-image: url('#');
}

<body class="unique"></body>

Use a class name on the body tag for that page only. Create a corresponding CSS declaration for that class.

I'm not sure if this is the best way to do this but I solved this problem in one of my apps by making two application layouts, one for the home page (home_application.html.erb ) and one for all other pages ( application.html.erb ). Put an id tag in your CSS file:

#home {
  background: url(example.jpg);
}

Make the application.html.erb :

<!DOCTYPE html>
<html>
  <head>
    header
  </head>

  <body>
    stuff
  </body>

</html>

Make the home_application.html.erb :

<body id="home">
    stuff
</body>

Then in your static_pages_controller (or whatever controller you use for your home page) put:

def home
    render 'layouts/home_application.html.erb'
end

This will render the layout with the background image for the home page and the layout for everything else for all other pages by only changing the id of the <body> tag.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM