2016-08-01 43 views
0

我試圖樣式一個div容器,並添加一個背景圖像,這是一個用戶上傳並存儲在數據庫(adventure.image.url)的圖像。我不確定如何在css文件中嵌入erb代碼。嵌入式軌道的CSS文件

下面是來自index.html.erb文件中的代碼:

<div class="adventure_container"> 
 
     <% @adventures.each do |adventure|%> 
 
     <div class="adventure"> 
 
      <%= link_to "#{adventure.title}", adventure_path(adventure.id), class: "adventure_title" %> 
 
      <%= (image_tag adventure.image.url(:medium), class:'adv_img') %> 
 
     </div> 
 
     <% end %> 
 
    </div>

這裏是CSS(或SCSS)的代碼,我想給圖像添加到作爲背景於:

.adventure { 
 
    display: flex; 
 
    text-align: center; 
 
    width: 300px; 
 
    height: 200px; 
 
    // background-color: #e9e8e8; 
 
    background-image: url() 
 
    margin: 1%; 
 
    // border: 1px solid purple; 
 
    border-radius: 15px; 
 
}

非常感謝。

回答

1

您可以使用內聯樣式是這樣的:

<%= link_to "#{adventure.title}", adventure_path(adventure.id), class: "adventure_title", :style => 'background-image: url('+adventure.image.url(:medium)+')' %> 
-1

請將更改添加到以下代碼。

<div class="adventure_container"> 
 
    <% @adventures.each do |adventure|%> 
 
    <div class="adventure"> 
 
     <%= link_to "#{adventure.title}", adventure_path(adventure.id), class: "adventure_title", style: "background-image: url(#{asset_path(adventure.image.url(:medium))});" %> 
 
    </div> 
 
    <% end %> 
 
</div>

或者

<div class="adventure_container"> 
 
    <% @adventures.each do |adventure|%> 
 
    <div class="adventure"> 
 
     <%= link_to "#{adventure.title}", adventure_path(adventure.id), class: "adventure_title", style: "background-image: url(#{asset_path(adventure.image.url(:medium))});" do %> 
 
     <%= (image_tag adventure.image.url(:medium), class:'adv_img') %> 
 
     <% end %> 
 
    </div> 
 
    <% end %> 
 
</div>

// I am not a css guy. But you get the idea to adjust the background div accordingly. 
 
.adventure { 
 
    display: relative; 
 
    // background-color: #e9e8e8; 
 
    // border: 1px solid purple; 
 
    border-radius: 15px; 
 
} 
 
.adv_img { 
 
    position: absolute; 
 
    text-align: center; 
 
    width: 300px; 
 
    height: 200px; 
 
    margin: 1%; 
 
}

+0

downvote的任何特定原因? – Minato

0

可以動態背景圖像添加到一個div像這樣:

<div class="adventure" style="background: url(<%= adventure.image.url(:medium) %>) no-repeat"> 
     <%= link_to "#{adventure.title}", adventure_path(adventure.id), class: "adventure_title" %> 
</div> 

,只是增加你的CSS。