Dynamic scss / sass background image assignment

What I want to do is to have a form in which you can upload the image, and then when you view this object, the image is rounded in the center, vertically and horizontally in a specific div. Its size is unknown, etc.

If there is a way to center it vertically using the image_tag helper, I like 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 images, and when I output @ object.image, it passes the path on my computer to the image (so I don’t know if the path or URL will be considered in production). Any ideas?

+4
source share
1 answer

You can use erb in the sass file, but this is really a very bad idea, since your css will have to be parsed for each request (and the browser will not be able to cache it).

I would recommend just sticking to one css snippet directly on the watch page in a style tag. Therefore, it is rated on the page. It makes sense?


UPDATE (adding requested example)

Add this to your actual view (e.g. 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 as it is not dynamic. @object.image should return the actual path to the image, so if @object.image is a ruby ​​object, you need to access any property that @object.image.path path ( @object.image.path or @object.image.url or something that suits your codebase).

+20
source

All Articles