How to give text or an image a transparent background using CSS?

Problem:

You want to put a background on the contents (texts or image) and make it transparent using opacity. But you don’t want to change opacity of your contents.

HTML:

<div class=content> Transparent background</div>

CSS:

.content{background:red;opacity:0.5}

By doing this, both background and text become in low opacity. You don’t want that. You need to fix it.

Solution:

If a color is used as background, use rgba value for background-color property.

The code:

.content{background-color:rgba(255,0,0,0.5);}

Explanation:

rgba is used to make color and opacity. (255,0,0) is for color and (0.5) for opacity. The advantage of rgba is that it doesn’t affect the child element.

If images are used as a background, add another <div> element to hold the background.

HTML:

<div class= “content”>
    <div class= “bg”></div>
    Transparent background
</div>

CSS:

.content {
    position: relative;
    z-index: 1;
}

.content .bg {
    position: absolute;
    z-index: -1;
    tiop: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: url(example.jpg);
    opacity: 0.4;
    width: 100%;
    height: 100%;
}

Explanation:

In the background section,”z-index:-1” is used. This results the background is placed behind the text. Here opacity is applied for background which has no effect on text. Because text isn’t child of background.