How to Create Faded Background using HTML, CSS, and JavaScript

Wednesday, November 9, 2022

In this article, we are going to learn how to create a faded background using HTML, CSS, and JavaScript.

Use case

This is particularly help when we want to add an overlay to our hero sections to add heading text. Suppose we have the following hero section on our website.

<!DOCTYPE html>
<html>
  <head>
    <title>Devtools Tech Sandbox</title>
    <meta charset="UTF-8" />
  </head>
  <body>
    <div class="hero">
      <h1>
        <strong>Mountains</strong> Are Calling
      </h1>
    </div>
  </body>
</html>    
.hero {
  width: 100%;
  height: 700px;
  background: url(https://images.unsplash.com/photo-1517048953202-826f67b3b313?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=3571&q=80);
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
  display: flex;
  align-items: center;
  padding: 30px;
  box-sizing: border-box;
}

.hero h1 {
  color: white;
  font-size: 70px;
  font-weight: 400;
}

Without Faded Background Output

Without faded background

Add Faded Background

The above section looks okay but we can make it better by adding a faded background to our background image. Let us update our hero class and a gradient to the background image.

.hero {
  width: 100%;
  height: 700px;
  background: linear-gradient(
    to right,
    rgba(0, 0, 0, .8), rgba(0, 0, 0, 0)
  ), url(https://images.unsplash.com/photo-1517048953202-826f67b3b313?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=3571&q=80);
  ...
}

We are adding a linear gradient that moves from left to right direction. On the left we are adding black color with 0.8 opacity (rgba(0, 0, 0, 0.8)) and we keep the right section transparent (rgba(0, 0, 0, 0)). Let us see the result below!

With Faded Background Output

With Faded Background

I hope this blog post helped you in some way. Please do share it and show our content much-needed love! 😄

Reach out to us here.

Unsure about your interview prep? Practice Mock Interviews with us!

Book Your Slot Now