Inserting a background-image from asset pipeline with tailwind

Viewed 1090

I've been trying to add a background picture with the help of Tailwind in my project but it won't work, I'm guessing because of an asset-pipeline conflict somewhere ?

What I've tried:

  • Inserting the image directly in my tailwind.config like so: 'essential-oil': "url('/assets/images/essential-oil.png')", 'essential-oil': "asset-url('essential-oil.png')"
  • Inserting the image directly in my HTML with a style: "background-image:url(/assets/images/essential-oil.png)
  • Putting my image in an other place in the app like Public

None of the solutions work. At worse, all of my style disappear from my HTML at best, the style looks ok but the picture is not there. Any idea ?

Thank you.

2 Answers

You can do the following:

  1. Move the image under the asset pipeline directory app/assets.
  2. Refer to the new asset in tailwind.config.js
module.exports = {
    theme: {
        extend: {
            backgroundImage: {
                'essential-oil': "url('essential-oil.png')"
            }
        }
    }
}
  1. Refer to the background image in the HTML
  <div class="bg-essential-oil">
  </div>

Details

This works since Sprockets has been changed to support fingerprinting plain url([asset-path]) references. See https://github.com/rails/sprockets-rails/pull/476. Make sure you're on Sprockets 3.3.0 or higher. I got the answer after I opened an issue on the tailwindcss-rails repository: https://github.com/rails/tailwindcss-rails/issues/137#issuecomment-1025853968.

By extension, it also works by putting the URL inline:

<div class="bg-[url('essential-oil.png')]">Has the essential oil background</div>

Reference

Rails Guide - The asset pipeline

  1. Move image into the public folder
  2. Refer to image in the tailwind.config.js
module.exports = {

  theme: {
    extend: {
      backgroundImage: {
       'hero-pattern': "url('/assets/icon-arrows-left.svg')",
      }
    }
  }
}
Related