Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Background Image with opacity in TailwindCSS

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 (using utilities)?

like image 267
Pranta Avatar asked May 20 '26 00:05

Pranta


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

like image 92
Crysfel Avatar answered May 22 '26 15:05

Crysfel