css :hover only affect top div of nest

前端 未结 4 941
再見小時候
再見小時候 2020-12-20 11:18

Hi: got some html like:

And some css like:

相关标签:
4条回答
  • 2020-12-20 11:42

    Have a look at http://jsfiddle.net/n6rzA/

    Code from there:

    <div class="c">
        <div class="c"></div>
    </div>
    
    .c:hover {border:solid 1px red}
    .c > .c:hover {border:solid 1px green}
    
    0 讨论(0)
  • 2020-12-20 11:43

    I got the desired result by reworking a bit the html and using only css.

    The HTML:

    <div class="wrapper" > 
      <div class="parent"></div>
      <div class="child"></div>
    </div>
    

    And the CSS:

    .wrapper {
      height: 500px;
      width: 500px;
      background-color: lightblue;
      position: relative;
    }
    
    .parent {
      height: 250px;
      width: 250px;
      background-color: lightgreen;
      top: 3em;
      left: 3em;
      position: absolute;
    }
    
    .parent:hover {
      border: 3px red solid;
    }
    
    .child {
      height: 50px;
      width: 50px;
      background-color: lightgrey;
      top: 5em;
      left: 5em;
      position: absolute;
    }
    
    .child:hover {
      border: 3px red solid;
    }
    

    https://jsfiddle.net/rafaelrozon/pynngjpk/

    Basically instead of nesting the divs they can be siblings and then you can use css to make them look nested.

    I hope it helps others.

    0 讨论(0)
  • 2020-12-20 11:54

    Old question, but for those that land here I solved the issue by rethinking the html a bit to make the CSS simple. This solved my problem when creating html/css for nested ul/li tree views. Adding an item class div:

    <div class="class" >
        <div class="item">Parent</div>
    
        <div class="class" >
          <div class="item">Child</div>
        </div>
    </div>
    

    Then I can apply CSS to "item" class and since item is not within item, ...within item, ...within item, the hover selector doesn't cascade up the node chain. So I colored the background of my tree view items on hover without splashing all parents.

    0 讨论(0)
  • 2020-12-20 11:57

    If the inner class is immediate child you can use the >. If it's not immediate child you can use space.

    So in first case .class > class:hover { } and in second case .class .class:hover { }

    First case : http://jsfiddle.net/wp4Jf/

    Second case : http://jsfiddle.net/wp4Jf/2

    Keep in mind that > works for ie8+

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