By Vivian
/May 24, 2022
There are multiple ways to work with background images using Tailwind but I’ll show you the 3 most common (and recommended) ways to do it on your project.
Let’s start the old-fashioned way, by adding it to the tailwind config. This is great if you want to reuse the image in multiple places in your project.
I recommend you add it in the extend object of your config, like this:
extend: {
backgroundImage: {
'hero': "url('../public/images/hero.jpg')",
},
}
Then in your HTML you use it like this:
<div class="bg-hero"></div>
style attribute:If you prefer to skip the config then you can just add it using the style attribute, like this:
<div style="background-image: url('../public/images/hero.jpg');"></div>
This is good if you plan to add more inline styles to your element or even perform some conditional logic with the image.
Now in V3, you can do this fancy syntax too. If you prefer not to use inline styles and have a single-use image then this is the best approach.
<div class="bg-[url('../public/images/hero.jpg')]"></div>
Following our example of a hero background image, once you have your image showing on your page then you’ll also want to:
bg-no-repeatbg-coverbg-centerbg-fixedHere’s the finished markup for you:
<div class="bg-hero bg-no-repeat bg-cover bg-center bg-fixed"></div>
Here’s also a Tailwind Play example you can play around with.
This is a pro tip for you, for example let’s say that you want to disable the background image in tablets and use a different image for desktop, this is where the arbitrary value approach really shines:
<div
class="
bg-no-repeat bg-cover bg-center
bg-[url('../public/images/hero-mobile.jpg')]
md:bg-none
xl:bg-[url('../public/images/hero-desktop.jpg')]
"></div>
That’s it for this one! I hope you learned the multiple ways to use background images with Tailwind CSS and how to use them on your project.