(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:
- Some nodes are to be always visible. They can be nested.
- Each of these nodes always has exactly one "info child node" which is to be shown only while its parent node is hovered. (There can possibly be other non-info child nodes, since those can be nested).
- I want only the info for the currently hovered node to be shown exclusively.
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)?
2
Answers
You are making a basic mistake your hovered parent contains a grandchild simply make a sibling hover condition and that will work
jsfiddle link
Add this CSS selector:
This selector works effectively to hide the
.info-on-parent-hover
elements when their sibling.always-visible
elements are being hovered. However, it’s important to note that the:has()
pseudo-class is not supported in all browsers, so its usage may be limited. In browsers that do not support it, you may need to use JavaScript based solution.