Home  »  Code Snippets   »   css set background opacity

The best way to make the background transparent is to use the transparent image with an alpha channel. There are alternative ways to achieve this opacity using CSS properties and filters. Let’s consider the following case to understand various techniques for making background transparent.

Structure

We'll use a simple structure and add an image as a background placeholder. We'll try to overlay a div block and apply transparency to the block using various colors and images.

here is how HTML structure will look like:

<div class="wrapper">
<img alt="" src="bathroom-bg.png" />
<div class="background"></div>
</div>

We're using a simple relatively positioned wrapper and an image that will act as a background placeholder.

the class background is what we use as our main layer. The CSS code will look like this:

.wrapper{position: relative;}
.background{ position:absolute; width: 28%;height: 48.6%;left: 36%;top: 23.2%; background:white;}

This will place a white solid on top of our image.

Edit Example

Using Opacity Filter

Now let's add a filter to make the layer transparent.

.background{background: #feefc3; filter: opacity(0.9);}

opacity filter can make the entire element transparent. meaning child within the div element will be transparent.

Edit Example

Using Opacity Property

opacity can be used good old property way. where we just specify numbers between 0-1 and the layer becomes transparent.

.background{background: #feefc3; opacity:0.9;}

The result will be exactly same as the opacity filter.

Edit Example

Using Transparent Colors

Transparency is also available in colors. The main benefit is the color itself is transparent and not the element. This will allow the inside element to stay opaque while the background remains transparent.

.background{background: rgb(254 239 195 / 87%);}

the color syntax can be any of supported color with alpha. That is: rgba / hasla

Edit Example

Using CSS Gradients

CSS Gradients can be another form of transparent background. One can create transparent gradient using transparent colors like this:

.background{background: linear-gradient(0,rgb(254 239 195 / 10%),rgb(254 239 195 / 100%));}

This will enable gradients in the background.

Edit Example

Using Images with Alpha

The simplest and most effective way is just to use transparent background images. PNG and WEBP support alpha channels.

.background{background: url(window.png) center/cover;}

What you'd see using the image:

Edit Example

This technique is applicable for any kind of element or pseudo-element. we can mix and match these techniques and use multiple images to adjust the entire composition.

 

Similar Tags:

+ more tags