Is there a css selector for selecting an element futherup in the html?

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, "");
});

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()


"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 ..