In TailwindCSS, adding background images is a little frustrating because there is no direct way to add background images. In this guide, you’ll learn 3 different ways to add background images in TailwindCSS.
Method 1: Using Arbitrary Value
You can use arbitrary values to add a background image to your webpage or a specific div element
. To add a background with an arbitrary value, you need to add url(url_of_image)
withbg-
. This method is recommended use if you are wishing to use the background just once in a project. An example to add a background image with an arbitrary value is given below which you can check online.
1 2 3 4 5 6 7 8 9 |
<div class="h-screen bg-[url(https://placekitten.com/1400)] bg-no-repeat"> </div> |
Method 2: Adding Background Image with Custom Class
You can add a custom class in the tailwind input file with the background image you want to use. Go to your tailwind input file and add a custom class with the backgroun image property and provide the url of your image. Here is a working demo of a custom class that adds a background image.
1 2 3 4 5 6 7 8 9 10 |
@tailwind base; @tailwind components; @tailwind utilities; .my-custom-bg-class{ background-image: url(path_to_image); } |
Method 3: Add Background to Tailwind Config File
The third method to add a background image in your TailwindCSS project is to add a background in the tailwind config file (tailwind.config.js)
. You need to extend the backgroundImage
property and add your custom background image. Here is a simple example to add a custom background image in the config file and then use it in your HTML.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
/** @type {import('tailwindcss').Config} */ module.exports = { theme: { extend: { backgroundImage:{ 'cats': 'url(path_to_image)' } }, }, plugins: [], } |
1 2 3 4 5 6 7 8 9 |
<div class="h-screen bg-cats bg-no-repeat "> </div> |
Here is a working demo of a custom background image in the config file.
Conclusion
There are 3 different ways to add background images in the TailwindCSS project. If you are using a background just once, use the arbitrary value with the image path. For a background image that you wish to use multiple times in your project, use the custom class or add a background in the tailwind config file.