动态分配背景图片 scss/sass [英] Dynamically assigning background image scss/sass

查看:151
本文介绍了动态分配背景图片 scss/sass的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的是有一个表单,您可以在其中上传图片,然后当您查看该对象时,图片会在特定 div 中居中、垂直和水平地向上倾斜.它的大小未知等.

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.

除非有一种方法可以使用 image_tag 助手将其垂直居中,否则我希望能够将图像用作背景图像.在我的 .css.scss 文件中,我希望能够执行类似

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
}

我使用 CarrierWave 上传图片,当我输出 @object.image 时,它​​会在我的计算机上提供图像的路径(所以我不知道在生产中是否会被视为路径或 url).有什么想法吗?

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?

推荐答案

可能在 sass 文件中使用 erb,但这是一个非常非常糟糕的主意,因为您的 css 必须是解析每个请求(浏览器将无法缓存它).

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

我建议只将那一段 css 直接粘贴在视图页面上的样式标记中.这样它就会与页面一起评估.有道理吗?

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(添加请求的示例)

将此添加到您的实际视图中(例如 show.html.erb):

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

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

您可以在 css 文件中保留 background-position 声明,因为它不是动态的.@object.image 需要返回图像的实际路径,所以如果 @object.image 是一个 ruby​​ 对象,你需要访问存储路径的任何属性(@object.image.path@object.image.url 或任何适合您的代码库的东西).

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

这篇关于动态分配背景图片 scss/sass的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆