How to work with background images in Tailwind CSS
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.
# Via the tailwind config:
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:
Then in your HTML you use it like this:
# Via the
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.
# Via using an arbitrary value:
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.
# But you’ll also need these properties
Following our example of a hero background image, once you have your image showing on your page then you’ll also want to:
- Make it not repeatable by using
- Have it use all the available space by adding
- Positioning it in the center by using
- This is option but you can also make it parallax with
Here’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.
# Disable/change the image in specific breakpoints
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:
bg-no-repeat bg-cover bg-center
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.
Sign up for Tailwind Weekly, our newsletter about
all things Tailwind CSS.
Check out a recent issue for a sample.