Only Applying a CSS Opacity to the Parent Container

November 16th, 2010 - Posted by Steve Marks to (X)HTML / CSS, Web Development.

If you’re reading this post you’ve probably realised by now that any elements included within a container that has had a CSS opacity applied will inherit this opacity also. Let’s look at a quick example of this scenario

The CSS:

body { background-color:#C00; }
.container { width:100%; }
.translucent {
	background-color:#FFF;
	opacity: 0.3;
	-moz-opacity: 0.3;
	filter:alpha(opacity=30);
}
.content { 
	width:100%; 
	opacity: 1;
	-moz-opacity: 1;
	filter:alpha(opacity=100);
}

The HTML:

<div class="container">
	<div class="translucent">
		<div class="content">
			Lorem ipsum dolor sit amet, 
			consectetur adipiscing elit.
		</div>
	</div>
</div>

The Result:

CSS Opacity Not Working

As you can see, our ‘content’ div has inherited the parents opacity. Even when we’ve specified full opacity it still doesn’t work as expected.

The Solution

The way to solve this is to lay the element containing the content over the top of the element with opacity set. By modifying the code above to achieve what we need we end up with the following:

The CSS:

body { background-color:#C00; }
.container { 
	position:relative; /* make any positioned child elements relative to this */
	width:100%; 
}
.translucent {
	position:absolute;
	top:0; /* Add a top and bottom position so the element */
	bottom:0; /* stretches to the height of the parent */
  	left:0;
	width:100%;
	background-color:#FFF;
	opacity: 0.3;
	-moz-opacity: 0.3;
	filter:alpha(opacity=30);
}
.content { 
	position: relative;
	width:100%; 
}

The HTML:

<div class="container">
	<div class="translucent"></div>
	<div class="content">
		Lorem ipsum dolor sit amet, 
		consectetur adipiscing elit.
	</div>
</div>

The Result:

CSS Opacity Working

As you can see, by overlaying the content over the background, the child does not then inherit the opacity set on it’s parent, or what was it’s parent anyway.

Note: The above code samples have had all margin, font and padding styles removed to simplify them. These will need to be added in manually to achieve what is shown in the example outputs.

Tags: ,
This entry was posted on Tuesday, November 16th, 2010 at 11:47 pm by +Steve Marks and is filed under (X)HTML / CSS, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.
Comments...

Fear not, we won't publish this

Comments (3)
  1. ziggy says:

    nice workaround! thx for sharing!

  2. Dudley says:

    SUPER helpful, thanks!

  3. Roee says:

    thanks for your hint