1

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?

1
  • Shouldn't img be div or any other element? Do you want to set a background image on an image? Commented May 18, 2020 at 10:27

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.