Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Background color for nested divs

Tags:

html

css

Is it possible for a child div to not inherit the background color of the parent div and instead inherit the background of the body tag?

Eg:

<body>
  <div id="main">
    <div id="sub">
       some content
     </div>
  </div>
</body>

body {
  background-image: url("blah");
}
#main {
  background-color: white;
}

The div sub would always inherit the background-color as white. But is there a way(work around) in CSS to specify that sub should not inherit the white color?? I read that CSS doesn't allow this but is there any work around for this?

like image 816
coder Avatar asked Nov 04 '22 15:11

coder


1 Answers

What you are asking is that there is a background image on the body, the body contains a div that has a white background color.

And then you want a div within this div that sees through to the background image? This is not possible.

There is a way to achieve what you want though, theoretically you could give the 'see-through' div the same background image as the body, and then through reading the coordinates with jQuery (or if the div is always in the same spot you could do it with css) you could position this background image so it overlaps with the body's image. This way it will look as if the inner div acts as a sort of window, achieving the effect you are looking for.

Like this:

http://jsfiddle.net/aFpAX/

jQuery method

You can get the window div's coordinates by using position(), and then set background-position with these values:

$(function(){

    var pos = $('#window').position();
    $('#window').css('background-position','-'+pos.left+'px -'+pos.top+'px');

});

You can see this in action here:

http://jsfiddle.net/aFpAX/2/

like image 181
Kokos Avatar answered Nov 11 '22 17:11

Kokos