htmlcssselector

Select only level being hovered, but not its parents or children


(I'm aware there's a myriad of CSS selector questions already, yet I couldn't find an answer to this one, unfortunately; so please bear with me.)

I have HTML with the following properties:

Example (here's a JSFiddle):

.always-visible {
  display: block;
}

.info-on-parent-hover {
  background-color: #ddd;
  font-weight: normal;
  font-style: italic;
  display: none;
}

.always-visible {
  font-weight: bold;
  background-color: #777;
}

.always-visible:hover {
  background-color: #3377cc;
}

.always-visible:hover>.info-on-parent-hover {
  display: block;
}
<div class="always-visible">
  node A [top-level node]
  <div class="info-on-parent-hover">some info about A</div>
</div>

<div class="always-visible">
  node B [top-level node]
  <div class="info-on-parent-hover">some info about B</div>

  <div class="always-visible">
    node C [child node of B]
    <div class="info-on-parent-hover">some info about C</div>
  </div>

  <div class="always-visible">
    node D [child node of B]
    <div class="info-on-parent-hover">some info about D</div>
  </div>
</div>

This works so far, more or less, but my goal is that only one 'info node' is shown at a time (i.e. the one belonging to its parent). So:

How can I select only the div class=".info-on-parent-hover" whose parent is currently hovered (and not those of its ancestors, siblings or descendants; i.e. when node D is hovered, node B's info must not also be shown)?


Solution

  • You are making a basic mistake: Your hovered parent contains a grandchild; simply make a sibling hover condition and it will work jsfiddle link

    .always-visible {
        display: block;
    }
    .info-on-parent-hover {
      background-color: #ddd;
      font-weight: normal;
      font-style: italic;
      display: none;
    }
    .always-visible {
      font-weight: bold;
      background-color: #777;
    }
    .always-visible .text-to-hover:hover {
      background-color: #3377cc;
    }
    .always-visible .text-to-hover:hover + .info-on-parent-hover {
        display: block;    
    }
    <div class="always-visible">
      <div class="text-to-hover">
      node A [top-level node]</div>
      <div class="info-on-parent-hover">some info about A</div>
    </div>
    
    <div class="always-visible">
      <div class="text-to-hover">
      node B [top-level node]
      </div>
      <div class="info-on-parent-hover">some info about B</div>
      
      <div class="always-visible">
      <div class="text-to-hover">
        node C [child node of B]
        </div>
        <div class="info-on-parent-hover">some info about C</div>
      </div>
    
      <div class="always-visible">
      <div class="text-to-hover">
      node D [child node of B]</div>
        <div class="info-on-parent-hover">some info about D</div>
      </div>
    </div>