Reputation: 749
I'm trying to change an entire page's body
's background color, when a user hovers over a thumbnail on that page (the thumbnail being in a div
within body
). Is there any way to do so using only CSS?
Upvotes: 1
Views: 1491
Reputation: 37169
Answer: NO.
You would have to go up, select the div
's parent and then the div
's parent parent... until you get to the body
. There is no way to select an element's parent using only CSS (if you'd like to know why, this article may prove useful)... yet (there will be a parent selector in CSS4, however).
JavaScript is the way to go if you want to do this and it's quite easy.
If you have something like this:
<div class='change-bg'></div>
in your HTML, then the JavaScript is simply:
var el = document.querySelector('.change-bg');
el.addEventListener('mouseover', function(){
document.body.style.backgroundColor = 'red';
}, true);
el.addEventListener('mouseout', function(){
document.body.style.backgroundColor = 'black';
}, true);
demo: http://jsfiddle.net/thebabydino/TDSUL/
If you're using jQuery, it gets even easier:
$('.change-bg').hover(function(){
$('body').css({'background': 'red'})},
function(){
$('body').css({'background': 'black'})
});
demo: http://jsfiddle.net/thebabydino/YWDeA/
Upvotes: 6
Reputation: 21676
Its not possible. Just go with JS, like example:
<div data-bgcolor="red"><div>
$("div").mouseover(function(){
$("body").css("background-color", $(this).attr("data-bgcolor"));
})
Upvotes: 1
Reputation: 354416
Not as such, no. You can change descendants' attributes but not ancestors' via CSS selectors. XPath would allow such things but that's not possible in CSS. So I guess you need to resort to JavaScript in this case.
Upvotes: 0