2

In my css I have this:

.inner-class {
  content: '';
}

.inner-class:before {
  background: url(http://www.fillmurray.com/500/500.jpg);
  content: '';
}

And in my view's html.erb, I have this:

<div class="outer-class">
  <div class="inner-class">
    ::before
  </div>
</div>

I want to change the ::before selector's properties using Rails. Normally, I would do something like this:

<div class="outer-class">
  <div class="inner-class" style:"background: url(<% image_path %>)">
    ::before
  </div>
</div>

However, that won't change the properties of inner-class:before. How do I do this?

1
  • you can't do it inline. Could append a style tag to head though Commented Aug 6, 2015 at 22:25

1 Answer 1

1

What you should do is add an additional CSS class, and change the ::before pseudo there, then apply that class conditionally to the parent element.

  1. Remove the ::before text from your ERB.
  2. Add a CSS class like so:
 .inner-class.do-something:before {
   background: url(http://www.fillmurray.com/300/300.jpg);
   content: '';
  1. Add in a conditional to your ERB like so:
 <div class="outer-class">
   <div class="inner-class" class="<% 'do-something' if my_condition %>">

   </div>
 </div>

Edit

Based on your comment, you're looking for something more like this. Fair warning this is probably the worst way to display an image dynamically in Rails I can imagine, and at this point I'd recommend you just have a separate element for your avatar image.

<div class='inner-class' data-image="<% ActiveSupport::Base64.encode64(open(article.user.avatar_url) { |io| io.read }) %>"></div>

Your CSS would be

 .inner-class:before { 
   content: url(attr(data-image)); 
   height: 40px; 
   width: 40px;  /* Whatever the expected height and width of the image are */`
 }
Sign up to request clarification or add additional context in comments.

5 Comments

I'm not sure if that helps me in this particular situation. I want to generate the image dynamically in the view, rather than set it in the css. So, something like <% article.user.avatar_url %> would be set as the background image in the ::before element.
I think I've decided to pursue another way of displaying the images after reading your comments, but I thought I'd try your method to see if I could get it to work. Trying it this way gives me an `uninitialized constant ActiveSupport::Base64" error.
Did you require 'base64'?
At the top of whatever file you're using the ActiveSupport::Base64.
If that would be `article.rb' in this instance, then yes. Sorry, I'm not very familiar with how that works.

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.