Share it:


CSS property Opacity has by birth issues i.e. it applies to all child div’s and makes them transparent. Opacity inheritance to child div’s is every day issue for web designers and front end developers. There are many solutions to fix the problem. Let’s understand different techniques to fix the issue, consider an example below.
Suppose we have a parent div id=”parent” and we want to make its background transparent while setting Opacity: 0.7 and we its child div has text hello world! We don’t want parent div’s Opacity to be applied on the text.

<div id="parent">
    <h2>Hello World!</h2>
</div>
#parent
{
	Opacity: 0.7;
	Background: #000;
	Padding: 7px 10px;
}

Amateur Solution

Easiest fix but not the best.
Set transparent image as a background to parent usually in a png format (Via my favorite Photoshop or any other graphics tool).

#parent
{
	Background-image: url(‘transparent-images.png’); /* Using transparent image to fix opacity inheritance issue in CSS */
	Padding: 7px 10px;
}

You are done!
Conclusion:
It is not a good practice to use an image when you can do it using CSS and HTML intelligently. Image adds unnecessary loading time which can be fixed.

Futuristic Solution

CSS3 rgba property, but its new as most of the browsers don’t support this feature. There for its not recommended to use if browser compatibility is your concern. For more about fall back and browser support for this property read here.

#parent {
   background: rgba(200, 54, 54, 0.5); 
}

Recommended Solution:

For this we need to change some HTML structure.

<div id="parent">
    <h2>Hello World!</h2>
    <div class=”transparent-bg”></div>
</div>
And the CSS
1
.transparent-bg
{
background: #000;
    	height: 80px;
    	width: 100%;
    	opacity: 0.3; 
}

Process:
Create a new div child of parent make it like the parent div. Remove opacity and other style from parent div and paste it to transparent-bg class. Now apply opacity on this div.
To adjust text over background by position: absolute.
Hurray! You are done!
More you can read on how to support opacity in different browsers here.

  • Francois

    very helpful me – specially the last method

    • http://aamirshahzad.net/ Aamir Shahzad

      i’m glad this helped you…

  • http://www.inaveed.com Naveed Ahmed

    Good Posting Aamir. I go with “Futuristic Solution”. I agree with Tyssen Design – John Faulds when it comes to absolute positioning; things got complex with absolute’ in responsive and compatibility.

    Consider adding ‘disqus’ to your blog for better commenting options. :) GR* JOB.

    • http://aamirshahzad.net/ Aamir Shahzad

      Thank you @Naveed bhai for kind words. Yes that is the right choice handling absolute elements is tough for responsive design. I have added ‘Disqus’ its great for comments.