Use :hover to modify the css of another class?

前端 未结 5 684
旧时难觅i
旧时难觅i 2020-11-29 01:44

Is there a way to modify the css for one class when hovering on an element from another class using only css ?

Something like:

.item:hover .wrapper {         


        
相关标签:
5条回答
  • 2020-11-29 02:15

    Provided .wrapper is inside .item, and provided you're either not in IE 6 or .item is an a tag, the CSS you have should work just fine. Do you have evidence to suggest it isn't?

    EDIT:

    CSS alone can't affect something not contained within it. To make this happen, format your menu like so:

    <ul class="menu">
        <li class="menuitem">
            <a href="destination">menu text</a>
            <ul class="menu">
                <li class="menuitem">
                    <a href="destination">part of pull-out menu</a>
    ... etc ...
    

    and your CSS like this:

    .menu .menu {
        display: none;
    }
    
    .menu .menuitem:hover .menu {
        display: block;
        float: left;
        // likely need to set top & left
    }
    
    0 讨论(0)
  • 2020-11-29 02:16

    You can do this.
    When hovering to the .item1, it will change the .item2 element.

    .item1 {
      size:100%;
    }
    
    .item1:hover
    {
       .item2 {
         border:none;
       }
    }
    
    .item2{
      border: solid 1px blue;
    }
    
    0 讨论(0)
  • 2020-11-29 02:38

    It's not possible in CSS at the moment, unless you want to select a child or sibling element (trivial and described in other answers here).

    For all other cases you'll need JavaScript. jQuery and frameworks like Angular can tackle this problem with relative ease.

    [Edit]

    With the new CSS (4) selector :has(), you'll be able to target parent elements/classes, making a CSS-Only solution viable in the near future!

    0 讨论(0)
  • 2020-11-29 02:38

    You can do it by making the following CSS. you can put here the css you need to affect child class in case of hover on the root

    .root:hover    .child {
       
    }

    0 讨论(0)
  • 2020-11-29 02:40

    There are two approaches you can take, to have a hovered element affect (E) another element (F):

    1. F is a child-element of E, or
    2. F is a later-sibling (or sibling's descendant) element of E (in that E appears in the mark-up/DOM before F):

    To illustrate the first of these options (F as a descendant/child of E):

    .item:hover .wrapper {
        color: #fff;
        background-color: #000;
    }​
    

    To demonstrate the second option, F being a sibling element of E:

    .item:hover ~ .wrapper {
        color: #fff;
        background-color: #000;
    }​
    

    In this example, if .wrapper was an immediate sibling of .item (with no other elements between the two) you could also use .item:hover + .wrapper.

    JS Fiddle demonstration.

    References:

    • CSS 2.1 selectors, at the W3.org.
    0 讨论(0)
提交回复
热议问题