Background color for nested divs
Is it poss开发者_Python百科ible 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?
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/
This is not possible anyhow, neither with CSS nor with JS also
If all you are using main
for is to create a border — i.e. there is no other content in it other than sub
— then perhaps you could use border
instead?
Or... Use PNG background images, with specific areas made "transparent".
Just remember to set the divs that you want to see through to background:transparent in css.
Or, you could consider using css variables in your stylesheet, as follows..
@variables {
bodyColor: #999;
divColor: #DDD;
}
body {
background-color: var(bodyColor);
}
#outerDiv {
background-color: var(divColor);
}
#innerDiv {
background-color: var(bodyColor);
}
精彩评论