Search code examples
javascriptjquerycssbackgroundbackground-image

How to inherit grandparent CSS not parent?


I have a feeling this won't be possible, but thought I'd ask anyway.

<body>                  //body uses 'back' background
<div id="div1">         //div1 uses 'front' background
   <div id="child1">    //child1: no backgrounds, so shows 'front' background
   </div>
</div>
</body>
  • My body element uses a background image. (I'll call it the back background image)
  • div1 uses a different background image (I'll call it the front background image), so the front background image covers over the main background image.
  • div1 contains a child div child1 that doesn't use any background images, so it just shows the background image of its parent i.e. it shows the front background.

I would like child1 to use the background of body and not the background of its parent div1. Because of the nature of the back background (it's a drawing, not a repeating pattern), I can't just apply the back background image to child1. I actually need a way to make a hole in div1's background so that child1 gets the back background image as its background, and not its parent's background.

So my question is: is there a way a div can inherit its grandparent's background, as opposed to its parent's background?

If this isn't possible with CSS, I'm open to javascript solutions.


Solution

  • This would be with using javascript and jQuery:

    CSS

    body {
       background: url("Background 1");
    }
    #div1 {
       background: url("Background 2");
    }
    #child1 {
       background: url("Background 1");
    }
    

    JS

    $(function() {
    
      function positionBackground() {
    
         var myChild1   = $("#child1");
         myChild1.css({
            backgroundPosition : "-" + myChild1.offset().left + "px -" + myChild1.offset().top + "px"
         });
      }
    
      positionBackground();
    
      $(window).resize(positionBackground);
    });
    

    Here is the fiddle: http://jsfiddle.net/gMK9G/