DEV Community

Vivian Guillen
Vivian Guillen

Posted on • Updated on • Originally published at

How to work with background images in Tailwind CSS

This post was originally posted on Design2Tailwind.

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:

  extend: {
      backgroundImage: {
        'hero': "url('../public/images/hero.jpg')",
Enter fullscreen mode Exit fullscreen mode

Then in your HTML you use it like this:

<div class="bg-hero"></div>
Enter fullscreen mode Exit fullscreen mode

Via the 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>
Enter fullscreen mode Exit fullscreen mode

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.

<div class="bg-[url('../public/images/hero.jpg')]"></div>
Enter fullscreen mode Exit fullscreen mode

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 bg-no-repeat
  • Have it use all the available space by adding bg-cover
  • Positioning it in the center by using bg-center
  • Possibly make it parallax with bg-fixed

Here’s the finished markup for you:

<div class="bg-hero bg-no-repeat bg-cover bg-center bg-fixed"></div>
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)