How to apply opacity only in the background with HTML and CSS

January 26, 2022

How to apply opacity only in the background with HTML and CSS

In this article we will learn how to apply opacity only in the background, that is, only the background div.  The content will not gain opacity.

apply opacity only in the background cover

Hey you  programmer, okay? Let’s learn to make only the background transparent! 😀

The idea here is to use an RGBA background-color and add the opacity

It might be a problem not to use hexadecimal as we’re used to, but it’s the easiest way to solve the problem

And we have several hex to RGBA converters on the internet

So look at the following example:

<div id="container">
 <p>Without opacity<p>

e created the #container that will have a transparent background, and the h1 and p elements cannot have opacity as it is our goal

See the CSS to achieve the ideal result:

body {
 margin: 50px;
 font-family: Helvetica;

#container {
 width: 500px;
 text-align: center;
 background-color: rgba(0, 0, 0, 0.1); 
 padding-top: 100px;
 padding-bottom: 100px;

#container h1, #container p {
 color: darkblue;

Let’s go to the result in the browser, and then explain the code:

First in the body we added some general styles to change the font and set up a margin

In the container, we defined a width with width and centered the content with text-align

In addition we inserted a background-color of 0,0,0 which means #000000 in hex, ie black color

And the last parameter controls opacity, transparency, and 0.1 means 10%

Then see that the white background appears fully, giving a whitish appearance to the #container div which should be black

And the contents (h1 and p) that are in darkblue color don’t suffer any impact with this

So we were able to apply transparency only to the background div, leaving the container elements intact


In this article we have seen opacity only in the background, leaving the div content without opacity

Which is often used when you need to show an image in the background and you want to insert text in front of it

Especially when the image is very clear

But it depends on the layout and the important thing is that we solved the problem, now you are able to create divs with opacity 🙂

Want to learn more about HTML and CSS? Click here!

Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x