Display next elements with same class, breakpoint end of array

64 views Asked by At

I have a little specific problem. This is my HTML structure:

<ul class="dropdown">
    <li class="level-1">Element 1 Level 1</li>
    <li class="level-2">Element 1 Level 2</li>
    <li class="level-2">Element 1 Level 2</li>
    <li class="level-2">Element 1 Level 2</li>
    <li class="level-1">Element 2 Level 1</li>
    <li class="level-1">Element 2 Level 1</li>
    <li class="level-1">Element 2 Level 1</li>
    <li class="level-2">Element 2 Level 2</li>
    <li class="level-2">Element 2 Level 2</li>
    <li class="level-2">Element 2 Level 2</li>
    <li class="level-2">Element 2 Level 2</li>
    <li class="level-2">Element 2 Level 2</li>
    <li class="level-1">Element 3 Level 1</li>
</ul>

Now, on Element 1 Level 1 hover, I need to display elements next to it with class level-2. Breakpoint is end of array of level-2 classes.

Expected result is showing every li with text Element 1 Level 2

Problem with:

li.level-1 + li.level-2 { display: block; }

Is that it will display only next element, not every element with level-2 class.

This need to work like dropdown with nested levels, but with this kind of structure.

Problem is that I need to solve this only with CSS or CSS3.

2

There are 2 answers

3
xaddict On BEST ANSWER

Normally one would put lower level items in separate ul's inside the li-item. The example you give is very bad practice since only humans can figure out it's actually a level lower in depth

BUT you should be able to do the following:

.level-2 {
    display:none;
}

.level-1:hover ~ .level-2 {
    display: block;
}

.level-1:hover ~ .level-1 ~ .level-2 {
    display: none;
}

The ~ means all items like x after this item so .level-1:hover ~ .level-2 means

all .level-2 items after a hovered .level-1 item

The next statement .level-1:hover ~ .level-1 ~ .level-2 is there to hide items with .level-2 áfter another .level-1 item.

NOTE: This doesn't help you much though as you will never be able to reach the lower depth items, because they disappear when you hover them.

EDIT: Also, this only works in relatively new browsers.

A good tree markup would be:

<ul>
  <li>
    <a>first level link</a>
    <ul>
      <li>
        <a>second level link</a>
      </li>
    </ul>
  </li>
</ul>

Then the markup would be easier and work cross-browser:

ul ul li {display:none;}
li:hover ul {display:block;}
3
Nilesh Mahajan On

You can use ~ selector in CSS just like in this fiddle https://jsfiddle.net/nileshmahaja/7nhy0yvn/

CSS

ul li {
    display:none;
}

ul li:first-child {
    display:block;
}

ul li:hover ~ li.level-2 {
    display:block;
}