DEV Community

loading...

How to Darken a Background Image with the New Tailwind CSS v2.2 Update

Mark
・1 min read

Originally posted on my website

Before Tailwind v2.2 you would have to do the following to darken a background image:

<section class="relative" style="background-image: url(https://images.unsplash.com/photo-1623929147463-fb46e69f0f05?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1334&q=80)">
  <div class="absolute inset-0 bg-black bg-opacity-50"></div>
  <div class="container mx-auto py-48 relative">
    <h1 class="text-white text-5xl font-bold text-center">
      Hello
    </h1>
  </div>
</section>
Enter fullscreen mode Exit fullscreen mode

Tailwind Play Example

This works fine but it does require an extra HTML element, usually a div 👎

But in Tailwind v2.2 you can do the following thanks to the new before and after psuedo variants:

<section class="relative before:absolute before:inset-0 before:bg-black/50" style="background-image: url(https://images.unsplash.com/photo-1623929147463-fb46e69f0f05?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1334&q=80)">
  <div class="container mx-auto py-48 relative">
    <h1 class="text-white text-5xl text-center">Hello</h1>
  </div>
</section>
Enter fullscreen mode Exit fullscreen mode

Tailwind Play Example

Much cleaner!

This example also makes use of the new and improved color opacity syntax replacing bg-black bg-opacity-50 with bg-black/50.

Read up on the full list of changes on the Tailwind CSS webite:

Tailwind v2.2

Discussion (0)