Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically assigning background image scss/sass

What I want to do is to have a form where you can upload a picture, then when you view that object, the picture cones up centered, vertically and horizontally in a specific div. The size of it is unknown, etc.

Unless there is a way to center it vertically with the image_tag helper, I like to be able to use the image as a background image. In my .css.scss file, I want to be able to do something like

.image_div {
     background-image: image_url("#{@object.image}");
     background-position: center
}

Im using CarrierWave to upload the pictures, and when I output @object.image it gives the path on my computer to the image (so I don't know if in production that would be considered the path or url). Any ideas?

like image 240
cadlac Avatar asked Dec 01 '22 04:12

cadlac


1 Answers

It's possible to use erb in a sass file, but it's a really, really bad idea, as your css will have to be parsed on each request (and the browser will be unable to cache it).

I'd recommend just sticking that one snippet of css directly on the view page in a style tag. That way it gets evaluated with the page. Make sense?


UPDATE (adding requested example)

Add this to your actual view (ex. show.html.erb):

<style media="screen">
  .image_div { background-image: url(<%= @object.image %>); }
</style>

You can leave the background-position declaration in the css file since it's not dynamic. @object.image needs to return the actual path to the image, so if @object.image is a ruby object, you'll need to access whatever property stores the path (@object.image.path or @object.image.url or whatever fits your codebase).

like image 187
Cade Avatar answered Dec 02 '22 16:12

Cade