DEV Community

Cover image for Creating an opaque cover with CSS
Uriel Bitton
Uriel Bitton

Posted on

Creating an opaque cover with CSS

Have you ever sees one of those fancy websites that display an image with some faded cover to make the text visible on top of the image?
Its a common design style in many websites and today we'll look at how to achieve and customize that design.

In my early days i remember trying to reproduce the effect, i tried editing the image itself in photoshop (most unpractical), then i tried adding an html element with a dark background and superimposing it on top of the image, i tried so many different ways to achieve what was essentially an extremely simple task with a few lines of CSS.
Sure all those methods worked but they were super unpractical and hard to reuse or they had many html elements and more css code than necessary.

Let's see how we can achieve this in the most efficient way with css, while adding no html at all.

Say we have our image inside a container with some text:

<div>
    <img src="bg-img.jpg" alt="bg"/>
    <h5>Horizon</h5>
</div>
Enter fullscreen mode Exit fullscreen mode

We're gonna add the background with just those html elements.

Here's our css:
We'll define a container sizes and the image inside it

div {
   width: 400px;
   height: 500px;  
}
div img {
    position: absolute;
     width: 100%;
     height: 100%;
     object-fit: cover;     
}
Enter fullscreen mode Exit fullscreen mode

This will create our image with 400px wide and 500px high.

Let's style our text

h5 {
    color: #fff;
    position: absolute;
    bottom: 20px;
    left: 0;
    right: 0;
    margin:auto;
    text-align:center;
    z-index:10;
    font-size: 40px;
}
Enter fullscreen mode Exit fullscreen mode

Now is where we add the opaque cover.
We'll create it with a simple pseudo-selector ::after

div::after {
        content: '';
        position: absolute;
        width: 100%;
        height: 100%;
        background: linear-gradient(0deg, rgba(0,0,0,1) 0%, rgba(0,0,0,0) 100%);
    }
Enter fullscreen mode Exit fullscreen mode

The content property is necessary, otherwise the browser won't display it. Then we set a full height and width. And finally we add the linear gradient property which starts at 0 opacity at the top and fades to full black background at the bottom to create that opaque effect.

And we're done! We've successfully created an opaque cover in the most efficient way possible, using as little code and no extra html elements.

Try it out and don't hesitate to share your thoughts!

Top comments (2)

Collapse
 
harrinsonariza profile image
Harrinson Ariza

Hello, Excellent tutorial. I made your tutorial with some modifications.
loving-kilby-6e23b8.netlify.app/
Thanks.

Collapse
 
urielbitton profile image
Uriel Bitton • Edited

Thanks! Glad you tried it for yourself :)