Background Image with opacity in tailwindcss

Viewed 12755

I am trying to recreate a project from vanilla CSS to tailwindcss. But I tried a lot of options and failed badly.

This is the CSS code:

header {
    background: linear-gradient(rgba(135, 80, 156, 0.9), rgba(135, 80, 156, 0.9)), url(img/hero-bg.jpg);
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center center;
    background-attachment: fixed;
    position: relative;
}

Can anyone transform this code to the equivalent tailwindcss code?

1 Answers

You have a few of options:

The easiest one is to set the image on the style property, after all this are very customized styles:

<header
  class="relative bg-fixed bg-center bg-cover bg-no-repeat"
  style="background-image:linear-gradient(rgba(135, 80, 156, 0.9), rgba(135, 80, 156, 0.9)), url(img/hero-bg.jpg)">
  
</header>

The second option is to keep using your stylesheet as it is now, but only for the background-image:

header {
  background-image:linear-gradient(rgba(135, 80, 156, 0.9), rgba(135, 80, 156, 0.9)), url(img/hero-bg.jpg)
}



<header class="relative bg-fixed bg-center bg-cover bg-no-repeat">
  
</header>

Finally, you can create a plugin where you can dynamically send the colors, and image as a parameter and tailwind will generate those classes for you. This is more complex but the documentation is really helpful: https://tailwindcss.com/docs/plugins#app

If you ask me, I'd just go with the first option

Here's a working demo and a tutorial: https://bleext.com/post/creating-a-hero-header-with-a-fixed-image

Related