Reputation: 294
I have a container element that somewhere in its tree contains another element, whose visibility should be toggled when hovering over the container element. This works fine
.container .toggle {
visibility: hidden;
}
.container:hover .toggle {
visibility: visible;
}
Problem is, when I nest two containers with separate .toggle
elements both elements are visible when hovering over the parent container.
The easiest fix is to change add a >
into the :hover
css selector. That works fine as long as the .toggle
element is a direct child of the .container
element.
In my use case I cannot guarantee that this is the case, the number of elements between the .container
and .toggle
element must be variable.
My best guess was a CSS the selector .container:hover *:not(.container) .toggle
trying to select every child of a container, that is not a child of another container... sadly that is not working
Here's the fiddle: http://www.w3schools.com/code/tryit.asp?filename=F0N00I8GETY0
Any hints welcome, thank you in advance :-)
Upvotes: 2
Views: 2547
Reputation:
If you are willing to stipulate the maximum nesting level, you can do this as follows.
div { outline: red 1px solid; }
/* Hide toggle elts by default. */
.toggle { visibility: hidden; }
/* Show toggle elts whose container is hovered. */
.container:hover .toggle { visibility: visible; }
/* Unless there is a non-hovered container in between! */
.container:hover .container:not(:hover) .toggle { visibility: hidden; }
<div class="container">
OUTSIDE CONTAINER
<div class="toggle">OUTSIDE TOGGLE</div>
<div class="container">
INSIDE CONTAINER
<div class="toggle">INSIDE TOGGLE</div>
</div>
To support three levels of nesting, you'd need a rule such as
.container:hover .container:hover .container:not(:hover) .toggle { visibility: hidden; }
Upvotes: 1
Reputation: 1725
If container is always in div, something like this could work
.container:hover div:not(.container) .toggle, .container .container:hover .toggle, .container:hover > .toggle {
visibility: visible;
}
Upvotes: 0
Reputation: 7207
the easiest thing I can think of is to toggle the visibility of the inner .toggle
elements to hidden
when toggling the parent .toggle
element.
.container .toggle {
visibility: hidden;
}
.container:hover .toggle {
visibility: visible;
}
.container:hover .toggle .toggle {
visibility: hidden;
}
but then again this code wont allow you to toggle the nested .toggle
elements' visibility, so you must add to the code above:
.toggle:hover .toggle {
visibility: visible;
}
but this only works as intended when you only have two nested .toggle
elements. And I'm afraid to say if you wanna toggle more nested elements you need to use js.
Upvotes: 0