skip to Main Content

I want to add a transparent black overlay over an img tag with some text in it, like in the example screenshot below. Ideally only with HTML and CSS.

I have been searching for hours and can’t find anything.

I know this could be easily done if the image is used as a background, but this isn’t an option for us (SEO reasons).

example overlay screenshot

2

Answers


  1. That shouldn’t be so bad. Would something like this work? First some HTML:

     #container {
          position: relative;
          width: 600px;
          height: 400px;
        }
    
        #someimg {
          postion: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
        }
    
        #overlay {
          position: absolute;
          top: 0;
          left: 0;
          clear: float;
          width: 100%;
          height: 100%;
          background-color: rgba(0, 0, 0, 0.6);
          color: #ffffff;
        }
       <html>
          <body>
            <div id="container">
              <img id="someimg" src="https://www.w3schools.com/w3images/fjords.jpg"</img>
              <div id="overlay">This is some text in an overlay</div>
            </div>
          </body>
        </html>
    Login or Signup to reply.
  2. Mic.com used the following code:

    .article-card-8col__overlay {
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      background: -webkit-linear-gradient(top,transparent,rgba(0,0,0,.9));
      background: linear-gradient(to bottom,transparent,rgba(0,0,0,.9));
    }
    

    I changed it slightly. You could also use their code with on a sibling div element of the image & the parent having position: relative; or use one like mine.

    .wrapper {
      position: relative;
      display: inline-block;
    }
    
    .wrapper:after{
      content: "";
      background: -webkit-linear-gradient(transparent,rgba(0,0,0,.9));
      background: linear-gradient(transparent,rgba(0,0,0,.9));
      position: absolute;
      display: block;
      width: 100%;
      top: 0;
      bottom: 0;
    }
    <div class="wrapper">
    <img src="https://thumbs.mic.com/MTAxZmJlOGIyMSMvYzNOMU1wRTJjMEdyWUZySS1UVjNnMV9LVkZRPS8xMngyNzM6NDk4MHgyODA5LzgwMHg0NTAvZmlsdGVyczpmb3JtYXQoanBlZyk6cXVhbGl0eSg4MCkvaHR0cHM6Ly9zMy5hbWF6b25hd3MuY29tL3BvbGljeW1pYy1pbWFnZXMvanQwY2dmZXZ5aW10aGhqZzBtYXc4cHZxNndrZmdwbmNqNzQzeTB4YmhybWtyOGc0YXYxcHVidWVldzU0OWIwcC5qcGc.jpg" />
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search