DEV Community

Cover image for How to Create an Overlay Effect with CSS
Shounak Das
Shounak Das

Posted on • Edited on

How to Create an Overlay Effect with CSS

CSS doesn't provide a straightforward way to add an overlay effect. But, we can create one easily with only two main properties, namely, z-index and opacity. In this quick post, I will showing you how to create one.

What we need to do is just move the overlay div above your text or image, and then make it partially transparent so that the content behind is visible. First things first, I will add a overlay div and some text inside a wrapper. Like this:

<div class="overlay-box">
  <div class="overlay"></div>
  <h1>Text</h1>
</div>
Enter fullscreen mode Exit fullscreen mode

Next, copy this CSS:

.overlay-box {
  position: relative;
  height: 200px;
  width: 400px;
}

.overlay {
  background: red;
  height: 100%;
  width: 100%;
  opacity: 0.7;  /* Must be translucent */
}

h1 {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  margin: 0;
  z-index: -1;  /* Your content must be under the overlay box */
}
Enter fullscreen mode Exit fullscreen mode

After adding all this, you should get something like this:

Alt Text


I hope you were able to learn something new today and liked it. Do share your thoughts on this in the comments below.

Happy Coding!😎

Top comments (0)