简体   繁体   中英

Css hover child to trigger effect on parent

I have this HTML code:

<span id="search">
 <input type="submit" value="" id="button">
</span>

I want to change the opacity of #search::after when hovering #button

#button:hover #search::after {opacity:1;}

It wont work so I wonder if its even possible to do this.

Using only CSS It's impossible.

What you can do is to use JavaScript/Jquery to trigger a action, like this:

$("#button").hover( function() {
   $(this).parent().addClass("hover");
});

and in your css:

#search.hover::after {opacity:1;}

Related: Is there a CSS parent selector?

This is not possible with just CSS. You might try using Javascript to help with this.

$("#button").on("mouseenter",function(e){
     $("#search:after").css({"opacity":1});
})

However, in order to make a selection with a pseudo class, you'll need the jQuery psuedo shim:

http://jquery.lukelutman.com/plugins/pseudo/jquery.pseudo.js

No that's not possible because CSS doesn't have a parent selector.

But if you can change your html markup, then you can use adjacent sibling selector +

 #button:hover + #search::after { content: "hovered" } 
 <input type="submit" value="hover me" id="button" /> <span id="search"></span> 

`

What is the size of your search container? Does it match the child? If so adding the hover to search will achieve the same effect. Otherwise you'll need to rearrange your markup or use javascript. I'm all for simple solutions though.

You Can Use Selector " + "

HTML

<a id="tooldrop">HOVER ME !</a>
<ul id="dropea">
  <li>ONE</li>
  <li>TWO</li>
</ul

CSS

    ul#dropea li{
        background-color: red;padding: 10px;opacity: 0;transition: all 0.3s ease-in-out;
    }
    #tooldrop:hover + ul#dropea li {
      transform: rotate(0) scale(1);
      opacity: 1;
    }

===========================================

JUST ADD "+" EVERY NEW ELEMENT

HTML

<a id="tooldrop">HOVER ME !</a>
<div class="block"></div>
<ul id="dropea">
  <li>ONE</li>
  <li>TWO</li>
</ul>

CSS

   ul#dropea li{
     background-color: red;padding: 10px;opacity: 0;transition: all 0.3s ease-in-out;
    }
    #tooldrop:hover + div.block + ul#dropea li {
      transform: rotate(0) scale(1);
      opacity: 1;
    }

ExteraDex 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM