Image in css. How do make that work

Hello,

I stored a image in assets/images

Now I need to use that image in my css as a background image. I can make it work bu then I have to rename my .css to .scsss.

Is there a way I can make it work without the renaming in Rails 6.1.4.1

Regards,

Roelof

I don’t recommend it, but you can turn off digest:

config.assets.digest = false

The problem is that this will also disable digests for CSS and Javascript files, so if you are using a CDN when you deploy a new version of your app you will need to manually reset its cache.

Is there a specific reason why you do not wish to rename css to scss? Maybe we can help you with that instead.

no perticular reason but I wonder why I have to do it and why I did not find that in the docs or tutorials

Files default to .scss because Rails assumes most people prefer writing SASS instead of pure CSS. So instead of this:

.button {
}
.button span{
}

You could do:

.button {
  span {
  }
}

That said, I’m not sure if Sprockets requires the file to be .scss, or as long as you use asset_url instead of url it will work:

.hero {
  background: asset_url('my-hero.jpg')
}

I think it need to be .scss I change it back to .css and use the asset-url but no luck

Try to change the suffix of your file from .css to .css.erb and change the content:

.hero {
  background: url('<%= asset_path('my-hero.jpg') %>');
}

If you are using the cssbundling gem, then it’s even easier than that. If you are writing SCSS, leave the .scss extension, likewise with .css. Don’t do anything besides writing a normal CSS image reference. Don’t add any helpers or ERB. The bundler will recognize the image reference and substitute a fingerprinted URL automatically.

.something {
background-image: url('kittens.png');
}

It will use the view lookup paths to resolve the location of the actual file, and add the content hash to the filename.

Walter

1 Like