- Instant help with your CSS coding problems

Set background image with TailwindCSS

Question:
How to set background image with TailwindCSS?
Answer:
<div class="bg-[url('/img/bg_small.jpg')] w-32 h-32"></div>
Description:

You can set background image in TailwindCSS using the arbitrary value syntax or you can modify the configuration to create custom utility class.

Set the background image with the arbitrary value syntax

You can use any background image in your template file using the arbitrary value syntax. This is useful if you cannot or do not want to modify the tailwind configuration file.

<div class="bg-[url('/img/bg_small.jpg')] w-32 h-32"></div>

If the background doesn't display correctly then check if the path is really correct. The best way is to check it on the developer console:

 

Set background image with Tailwind configuration

You can extend Tailwind configuration with background images and then use the custom utility class where you want the background image.

First list all of your background images in the tailwind.config.js file:

module.exports = {
  content: ['**/*.html'],
  theme: {
    extend: {
      backgroundImage: {
        'demo-bg-xl': "url('/img/bg_large.jpg')",
        'demo-bg-md': "url('/img/bg_medium.jpg')",
        'demo-bg-sm': "url('/img/bg_small.jpg')",
      }
    },
  },
  plugins: [],
}

As a result you can write code with auto completition like this:

<div class="bg-demo-bg-md w-32 h-32"></div>

 

Share "How to set background image with TailwindCSS?"
Interesting things
OpanAi's ChatGPT