1

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?

Peon
  • 7,216
  • 7
  • 45
  • 87
John Doe
  • 599
  • 1
  • 6
  • 13

3 Answers3

6

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/

Ana
  • 33,368
  • 6
  • 74
  • 119
1

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"));
})
Grzegorz Kaczan
  • 17,728
  • 3
  • 16
  • 17
0

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.

Joey
  • 316,376
  • 76
  • 642
  • 652