pau
pau

Reputation: 98

Using Ruby in CSS file

I want to set the img as a background image, however, I am not sure how to do it. My code in HTML is specified as

Ideally I would love something like:

img {
    background-image: url(<%= image_tag @destination.image_url %>);
}

But I know it is not really possible. Any ideas how can I implement it?

Upvotes: 1

Views: 165

Answers (1)

Smek
Smek

Reputation: 1208

Well your css.erb or scss.erb files are compiled to css in the end. So your inline erb would not work after compilation. I'm not sure if it could be configured to recompile on every request but I don't think it is ideal to do that because it would make your web pages very slow.

The image_tag helper is for creating an img tag to your html. So what you get now in your css is something like this:

img {
    background-image: url(<img src="path/to/image_url.jpg" >);
}

I don't think that's what you're after.

I think you should be able to add the img to your html instead of adding it in your css and then add some css to make it fill the wrapper.

<body>
<div class="wrapper">
<%= image_tag @destination.image_url, class: 'background-img' %>
</div>
</body>

.wrapper {
  width: 100%;
  height: 300px;
  position: relative;
}

.background-img {
  position: absolute;
  width: 100%;
  height: 100%;
}
<div class="wrapper">
<img src="https://via.placeholder.com/300" class="background-img">
</div>

Please note that I have used a div tag instead of an img tag.

Another option is to add some inline css:

.wrapper {
  width: 100%;
  height: 300px;
  background-repeat: no-repeat;
}
<div class="wrapper" style="background-image: url(https://via.placeholder.com/300)"></div>

Upvotes: 1

Related Questions