Take the 2-minute tour ×

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?

share|improve this question

1 Answer 1

up vote 9 down vote accepted

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 %>); }

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).

share|improve this answer
Inline styles on the element in question would make sense as well. –  cimmanon Jan 24 '13 at 13:39
I found a solution that works - since I know the size I want it to be, I used minimagick and carrierwave to resize the picture, using gravity => center. Although both of your options sound great, I could not get either of them to work. Perhaps an example? –  cadlac Jan 24 '13 at 21:11
@Cade I got yours working - it won't work for : image-url('erb image_url') but it works with the standard css url('erb image_url') –  cadlac Jan 24 '13 at 21:28
@cimmanon whenever I set the display to inline on the parent div, I cant reduce the height and whenever I set the display to table-cell on the parent div, the width comes out as 1px and I can't change that. Any ideas on what I'm doing wrong? –  cadlac Jan 24 '13 at 21:30
Inline styles as in <div class="image_div" style="background: url(filename); width: X; height: Y" />. –  cimmanon Jan 24 '13 at 21:36

Your Answer


