4

I just ran into a really wierd issue when setting opacity on a web page. The element with opacity obscures other elements on the page.This happens in Safari, Chrome and Firefox. Opacity is ignored in IE7 & 8. Not tested on IE9.

Fiddle

<style>
   #content { opacity: .92; background: #dfd; height: 300px;}
   #sidebar { width: 200px; float: right; background: #fdd; height: 200px; }
</style>
<div id="sidebar"></div>
<div id="content"></div>

Removing opacity restores the expected behavior. Another possible fix is to use rgba background values instead of opacity.

Has anyone else encountered this? If so, how did you fix it?

B2K
  • 2,541
  • 1
  • 22
  • 34
  • Possible duplicate of http://stackoverflow.com/questions/2837057/what-has-bigger-priority-opacity-or-z-index-in-browsers – Anoop Mar 21 '13 at 21:11
  • 1
    `#content` has a higher z-index than `#sidebar`. Since you aren't using `overflow:hidden;`, `#content` will overlap the floated `#sidebar`. – Shmiddty Mar 21 '13 at 21:13
  • 1
    http://jsfiddle.net/V4MrH/1/ – Shmiddty Mar 21 '13 at 21:13
  • Thanks for your response @Shmiddty, just not sure I want to force overflow: hidden. I updated my website to use an rgba background. – B2K Mar 21 '13 at 22:04
  • I've updated the fiddle with the rgba solution http://jsfiddle.net/V4MrH/28/ – B2K Jan 08 '15 at 20:03

2 Answers2

6

The opacity you're setting on #content is creating a new stacking context, and stacking contexts affect z-indexes. Since you didn't specify z-indexes manually, they're being auto assigned, and #content has a higher value than #sidebar because it comes later in the markup.

A simple CSS solution: just add position: relative; z-index: 2 to #sidebar (to establish yet another stacking context). On your real code, you may need to add a z-index to #content too, if you have more elements under #wrapper:

#sidebar { position: relative; z-index: 2; /* etc */ }

http://jsfiddle.net/V4MrH/3/

bfavaretto
  • 71,580
  • 16
  • 111
  • 150
  • So this is by design, but rather counter-intuitive, that adding opacity to an object would affect the layout of a web page. – B2K Mar 21 '13 at 21:54
  • Yes, it's totally counter-intuitive. But once you find out how it works, it actually makes sense. – bfavaretto Mar 21 '13 at 22:07
  • I tried using position: relative to fix the problem, but with no luck. http://jsfiddle.net/WzvLU/1/ This doesn't make sense to me. – Luke Aug 16 '13 at 18:13
  • @Luke I'm not sure what you're trying to do and what the problem is. I believe you should post your own question! – bfavaretto Aug 16 '13 at 18:16
3

This issue is already known. https://www.google.com/#q=opacity%20change%20z-index

You should use rgba background, which is also a widely supported property.

Romain Pellerin
  • 2,470
  • 3
  • 27
  • 36
  • I just made this the accepted answer, since it's what actually solved my problem. – B2K Jan 08 '15 at 19:57