In the following HTML, I want to apply a hover effect to the header h2
, upon hover of the image img
. Is there a css selector to do that, or another
There is actualy no way to do it in pure CSS.
But, you could simply do the following :
<article>
<a href="#">
<h2>Title</h2>
<img src="#" />
</a>
</article>
And then apply the :hover effect to the a
tag.
Another way will be with some javascript. For example, with the jquery selector .closest()
You could perhaps try a simple workaround, something like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style media="all">
h2 {position: relative; padding-bottom: 100px; line-height: 1.5em;}
h2 img {position: absolute; left: 0; top: 1.5em; width: 100px; height: 100px; background: yellow;}
h2 a:hover {color: red;}
</style>
</head>
<body>
<article>
<h2><a href="#">Title <img src="#" /></a></h2>
</article>
</body>
</html>
This is a rough hewn experiment, but no doubt could be refined. It's also legal, in HTML5, to nest the heading (and image) inside the a
, but I'm not a great fan of that.
Update: The subject specifier appears to have been removed from the Editor’s Draft, 6 May 2014 of the Selectors Level 4 specification. This leaves no way to achieve this using CSS.
Selectors Level 4 introduces the subject specifier which allows:
!h2 + a img:hover { }
to select the <h2>
.
Browser support is, AFAIK, currently non-existent.
You can simulate it in JavaScript (the following is untested, but should give you the idea).
var img = document.querySelector('h2 + a img');
img.addEventListener('mouseover', function (e) {
this.parentNode.previousElementSibling.className += " hovered";
});
img.addEventListener('mouseout', function (e) {
this.parentNode.previousElementSibling.className = this.parentNode.previousElementSibling.className.replace(/\shovered/g, "");
});
"Is there a css selector to do that?"
This doesn't exist in the current state of CSS yet (as of Selectors Level 3) .. but when Selectors Level 4 is more widely implemeneted, there will be a parent selector:
E! > F - "An E element, parent of an F element"
Unfortuntely it will be quite some time before this is implemented as the Module is still in the Working Draft stage ..