How to use background image in Tailwind CSS ?

How to use background image in Tailwind CSS ?

Simple tutorial to help you to stop using in the bad way background image property in Tailwind CSS

You must be familiar with tailwind CSS and its functions. If not, no problem; check a preview on tailwindcss documentation. Anyway, it's a great tool that I recommend for quick front-end app creation.

As in CSS, we have the option of using background tailwind CSS. Really? I'll demonstrate how I typically apply it in my projects.

Basics setup configuration

I currently use tailwindcss 3.0.24

//package.json
 "devDependencies": {
    "tailwindcss": "^3.0.24"
  }

Assume we're going to create this block or portion of the page with a background image property.

![](cdn.hashnode.com/res/hashnode/image/upload/.. align="middle")

Let's look at the HTML basic

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Background Image - Tailwind css</title>
    <link rel="stylesheet" href="./css/style.css">

</head>

<body class="font-poppins text-gray-800 overflow-x-hidden" id="top">

    <div class="w-full h-screen flex justify-center items-center text-4xl text-gray-900/80 font-bold">Welcome to
        tailwind</div>

    <!-- Main JS -->
    <script src="./js/main.js"></script>
</body>

</html>

Great, you can utilize any of the three methods:

  1. First way: Via the tailwind config

    It can be added to the tailwind configuration. If you want to use the image several times in your project, this is fantastic.

 extend: {
    backgroundImage: {
        'hero': "url('../public/images/hero.jpg')",
    },
}

So you can add class bg-hero like this

<div class="bg-hero"></div>
  1. Second way: Via the style

Yeah, I’m not joking if you want to use a simple method just use the old CSS style attribute.

<div style="background-image: url('../public/images/hero.jpg');"></div>
  1. Last way: using an arbitrary value

With v3 of tailwindcss, you use a background image with syntax too (my favorite).

<div class="bg-[url('../images/hero.jpg')]"></div>

You can also use others class like

  • bg-no-repeat (for no repeating image)

  • bg-cover (for use all the available space)

  • bg-center (for Positioning )

With them, your design can be enhanced further.

This one is done, thank you! I hope you learned how to use background images on your project and the various ways you can use them with Tailwind CSS. See you the next time for another article.