How to change the opacity of an element's background without affecting the child elements or text content

Topic: HTML / CSSPrev|Next

Answer: Use the CSS RGBA colors

There is no CSS property like background-opacity that you can use only for changing the opacity or transparency of an element's background without affecting the child elements, on the other hand if you will try to use the CSS opacity property it will not only changes the opacity of background but changes the opacity of all the child elements as well.

In such situation you can use RGBA color introduced in CSS3 that includes alpha transparency as part of the color value. Using RGBA color you can set the color of the background as well as its transparency. Learn more about CSS color values.

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="utf-8">
  • <title>CSS Opacity Using RGBA Colors</title>
  • <style type="text/css">
  •     body {
  •         background-image: url("images/pattern.jpg");
  •     }
  •     p{
  •         padding: 20px;
  •         background: rgba(0, 0, 0, 0.6);
  •         color: #fff;
  •         font: 18px Arial, sans-serif;
  •     }
  • </style>
  • </head>
  • <body>
  •     <p>Setting background transparency without affecting the text content.</p>
  • </body>
  • </html>

Alternatively, you can use transparent PNG images. Check out the tutorial on CSS Opacity to learn more about setting text in a transparent box.

Your Feedback:

We would love to hear from you, please drop us a line.