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?
-
http://stackoverflow.com/questions/8114657/how-to-style-the-parent-element-when-hovering-a-child-element – Reto Aebersold Jul 21 '12 at 23:44
3 Answers
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'})
});

- 35,599
- 6
- 80
- 131
-
I find it best to add it to the bottom of the page and inside of a $(document).ready(function(){...}); – ImaginedDesign Apr 11 '13 at 15:02
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"));
})

- 21,186
- 3
- 19
- 17
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.

- 344,408
- 85
- 689
- 683