views:

273

answers:

4

I'm trying to fade all elements on a webpage except for one div. I've been able to fade all the elements with the following jQuery:

$('*').css('opacity', .3);

However, it seems as if opacity is a property that inherits from parent elements, even if I explicitly set the opacity of the div to 1. I'm drawing a blank as to any solutions right now, so can I have some help here?

+1  A: 

Maybe instead of doing the * selector you can make it more targeted to divs or whatnot and then use the not selector to ignore the one you want to stay normal?

There's also this article on CSS Opacity that doesn't affect children that might be useful.

R0MANARMY
A: 

Opacity is indeed inherited. If you think about it, it doesn't make a lot of sense for a transparent div to contain a non-transparent div anyway.

What you probably wish to do instead is set the background color of a div to transparent. To do this, you need to use rgba colors but keep in mind this is supported in less browsers.

You can read a comparison of the two including their effects and implementations, here.

More information would be helpful. If the div in question is sufficiently separated from the rest of the content such that, occasionally, you wish to display it in isolation of everything else, you may wish to consider restructuring the page so that it is not contained in the parent div.

Rupert
+5  A: 

If what you want is to make this particular div stand out visually, you might consider an approach like the one that is used for modal windows/lightboxes. Position the div absolutely with a high z-index, and then stack another div in between the highlighted one and the rest of the content with a dark background color and medium opacity. That will in effect "dim" the rest of the page while still keeping the highlighted div with its normal apperance.

Jimmy Cuadra
+1  A: 

As Jimmy Cuadra suggested, you could change the position of the div then add an overlay under it... This is similar to what jQuery Tools Expose does.

You don't really need a plugin to do this though, I answered another question with a similar approach. This script will remove the overlay if you click anywhere outside of the highlighted div. Note this requires you to use jQuery version 1.4+

 // Relatively position the div to highlight
 $('#myDiv').css({
  position: 'relative',
  top     : 0,
  left    : 0,
  zIndex  : 100
 });

 // Add overlay and make clickable
 var w = $(window).width();
 var h = $(window).height();
 var $overlay = $('<div/>', {
  'id': 'overlay',
  css: {
   position   : 'absolute',
   height     : h + 'px',
   width      : w + 'px',
   left       : 0,
   top        : 0,
   background : '#000',
   opacity    : 0.5,
   zIndex     : 99
  }
 }).appendTo('body');
 // Click overlay to remove
 $('#overlay').click(function(){
  $(this).remove();
 })
fudgey