CSS sets the transparency of the background image without affecting the text
Setting transparency in background https://coder-cafe.com/wp-content/uploads/2025/09/images without affecting text with CSS
In this article, we’ll show you how to use CSS to set transparency in background https://coder-cafe.com/wp-content/uploads/2025/09/images while keeping text opaque. In some cases, we may want to achieve a special effect by changing the transparency of a background image without affecting the readability of the text. Below, we’ll introduce two common methods for achieving this effect.
Read more: CSS Tutorial
Method 1: Using Pseudo-Elements
The first method uses a pseudo-element as the background layer. This allows us to control its transparency independently without affecting the opacity of the text.
<div class="container">
<div class="background"></div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer id risus lectus.</p>
</div>
.container {
position: relative;
}
.background {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-image: url("background.jpg");
opacity: 0.7;
}
p {
position: relative;
z-index: 1;
}
In this example, we first create a container to contain the text and background layers. The background layer is absolutely positioned and overlays the text. By setting the background layer’s opacity to 0.7, we achieve a semi-transparent effect. Furthermore, by relative positioning the text element and setting its z-index to 1, we ensure that the text stays above the background layer, unaffected by the background’s opacity.
Method 2: Using a Transparent Background Color
The second method achieves a separation effect by setting the background color’s opacity, rather than the background image’s.
<div class="container">
<p class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer id risus lectus.</p>
</div>
.container {
background-image: url("background.jpg");
background-size: cover;
background-color: rgba(0, 0, 0, 0.7);
padding: 20px;
}
.text {
color: white;
}
In this example, we set the container’s background image and set the background color’s opacity to 0.7 using the RGBA color scheme. We also set the text element to a white color to contrast against the semi-transparent background. This also creates a separation between the background layer and the text.
Summary
By using pseudo-elements or transparent background colors, we can achieve transparency in CSS while maintaining the opacity of the text. These techniques are often used to create interesting visual effects in design and can be used to achieve unique background effects without reducing text readability. We hope this article was helpful!