I'm trying to make a background image transparent (no option to make a transparent PNG or lighter image, the images are changed often).
background: url(image.jpg) no-repeat center center / cover;
opacity: 0.2;
Got the image is working, but everything inside the DIV is transparent too. I've searched for a solution, but can't seem to implement the right one. Any pointer on how to fix that?
Example explained First, we create a <div> element (class="background") with a background image, and a border. Then we create another <div> (class="transbox") inside the first <div>. The <div class="transbox"> have a background color, and a border - the div is transparent.
There's no CSS property that you can use to change the opacity of only the background image. Unlike background colors, which allow you to adjust the alpha channel to control opacity, it simply doesn't exist for the background-image property.
The percentage of opacity is calculated as Opacity% = Opacity * 100 To set the opacity only to the background and not the text inside it. It can be set by using the RGBA color values instead of the opacity property because using the opacity property can make the text inside it fully transparent element.
To achieve this, use a color value which has an alpha channel—such as rgba. As with opacity , a value of 1 for the alpha channel value makes the color fully opaque. Therefore background-color: rgba(0,0,0,. 5); will set the background color to 50% opacity.
You can use CSS linear-gradient()
with rgba()
.
div {
width: 300px;
height: 200px;
background: linear-gradient(rgba(255,255,255,.5), rgba(255,255,255,.5)), url("https://i.imgur.com/xnh5x47.jpg");
}
span {
background: black;
color: white;
}
<div><span>Hello world.</span></div>
jsFiddle
Explanation:
The first part: linear-gradient(rgba(255,255,255,.5), rgba(255,255,255,.5))
creates a semi-transparent white background color. You can change the alpha parameter as needed between 0
(fully transparent) and 1
(fully opaque).
The second part: url("https://i.imgur.com/xnh5x47.jpg")
is to display the actual background image.
Together: background: linear-gradient(...), url(...);
creates multiple backgrounds, two of them are stacked, the first one covers the second.
Use opacity on the background div inside of the wrapper element.
.page {
position: relative;
width: 100px;
height: 100px;
}
.page::before {
content: '';
display: block;
position: absolute;
width: 100%;
height: 100%;
background: url('http://www.visitnorwich.co.uk/assets/Uploads/Events-images/Theatre-generic.jpg');
opacity: 0.2;
z-index: -1;
}
.box {
display: inline;
background: red;
}
<div class="page">
My page
<div class="box">Red box</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With