Is there a way to have display none on divs levelOne to levelFour when I hover one levelFive by just using CSS?
My Html Structure is below:
<div class="dropDownMenus levelOne"></div>
<div class="dropDownMenus levelTwo"></div>
<div class="dropDownMenus levelThree"></div>
<div class="dropDownMenus levelFour"></div>
<div class="dropDownMenus levelFive"></div>
My CSS looks like this:
.levelFour {
&:has(+ .levelFive) {
display: none;
}
}
This effectively hides the levelFour div right above levelFive, but is there a way to do so on hover.
4
Answers
Unfortunately, CSS alone does not provide a way to select and style preceding siblings. However, you can achieve the desired effect using a combination of JavaScript and CSS. Here’s a possible solution:
HTML:
CSS:
JavaScript:
With this solution, when you hover over the levelFive element, the JavaScript function hidePrecedingSiblings() will be triggered, which will hide all preceding siblings with the class dropDownMenus. This gives you the desired effect of hiding the levelFour, levelThree, levelTwo, and levelOne divs when you hover over the levelFive div.
Remember to adjust the CSS styles and class names according to your specific design requirements.
This won’t work without the wrapper, but with the wrapper and the reasonable modern
:has
selector, you could easily use something like this:Snippet:
This matches any elements having in the next siblings any element with
.levelFour
class:unfortunately with only css you will not be able to do it as
:has
is not yet support by all browserAt the date of this message (07/2023) the near bad solution in pure css can be to hide with a blank square other top value
or if you want to guard 5 item at same place