【问题标题】:How to add an inline background image?如何添加内嵌背景图片?
【发布时间】:2015-05-04 10:04:16
【问题描述】:

我正在尝试将静态 html 页面转换为 rails 页面。

我将如何转换以下行

<div class="item active" style="background-image: url(../../foo.png);">

图片位于assets/images 文件夹内。

如果它是标准图像而不是背景图像,我会使用image_tag

将内联样式删除到 css 文件中会更好吗?如果是这样,css 的外观如何?

.item .active {
background-image: url(assets/foo.png);
}

【问题讨论】:

  • 完全正确...将样式写入外部 css 文件被认为是一种很好的做法,原因有很多。
  • 没错。你有什么问题吗?
  • 使用 .item.active 类来应用 css。

标签: html css ruby-on-rails


【解决方案1】:

最好将 css 代码分开,以便将来重复使用。 你可以这样...

.item.active {
    background-image: image_url("foo.png");
 }

无需输入/assets/,别忘了输入rake assets:precompile

关于内联和外联使用css的优缺点,click here

【讨论】:

    【解决方案2】:

    从这里

    <div class="item active" style="background-image: url(../../foo.png);">
    

    css 是

    .item.active {
        background-image: image_url("foo.png");
     }
    

    这表明该 div 有 both 类。我们不知道您的具体情况,可能不是您所追求的。

    可能该图像仅适用于.active 类或仅适用于.item 类。

    那么 CSS 将只包含一个 single 类名,例如

    .active {
        background-image: image_url("foo.png");
     }
    

    这个

    .item .active {
        background-image: image_url("foo.png");
     }
    

    .active类是.item类的后代时,

    【讨论】:

    • 你的答案解释得很好。 :)
    猜你喜欢
    • 2016-06-23
    • 2020-07-09
    • 2018-04-08
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多