Tip #2: Create faded background images using linear gradients

  • — Frontend

  • 1 min. read

  • — 2/12/2023

Stop using Photoshop to add a gradient on top of your images so you can fade them into background! Instead, let me know show you how you can do it with just HTML and CSS.

Start by placing your image in a div with a class of relative:

<div class="relative">
  <img src="https://picsum.photos/1920/1080" width="1920" height="1080">
</div>
ℹ️
Make sure to include a width and height attribute on your img tag for better accessibility and to reduce layout shifting!

Then, create another div as a sibling of your img tag. This is where you'll put your linear gradient too:

<div class="relative">
  <img src="https://picsum.photos/1920/1080" width="1920" height="1080">
  <div class="bg-gradient-to-b from-transparent to-gray-900" />
</div>

So far you should only see the background image and not the gradient.

To fix this, add absolute inset-0 to your div with the linear gradient:

<div class="relative">
  <img src="https://picsum.photos/1920/1080" width="1920" height="1080">
  <div class="absolute inset-0 bg-gradient-to-b from-transparent to-gray-900" />
</div>

Here, absolute and inset-0 tell the linear gradient div to take up the full width and height of the div with the relative class (which just so happens to have the exact same width and height as your image).

Grab the code for this tip over at Tailwind Play.

Shaun Chander

hey (again), I'm shaun

I'm posting 3 tips on creative web development daily. Subscribe below to to get tips delivered straight into your inbox!