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

前端 未结 4 1330
温柔的废话
温柔的废话 2020-11-29 13:02

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

相关标签:
4条回答
  • 2020-11-29 13:22

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

    0 讨论(0)
  • 2020-11-29 13:25

    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.

    0 讨论(0)
  • 2020-11-29 13:28

    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, "");
    });
    
    0 讨论(0)
  • 2020-11-29 13:39

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

    0 讨论(0)
提交回复
热议问题