2

Here is my code as simple as possible for convenience.

            #hidden {
              display: none;
            }
            #visible:hover + #hidden {
              display: block;
            }
<html>

<head>

</head>

<body>
  <ul>
    <li id="visible">
      Names
      <ul id="hidden">
        <li>name 1</li>
        <li>name 2</li>
        <li>name 3</li>
        <li>name 4</li>
      </ul>
    </li>

  </ul>
</body>

</html>

So I have tried to follow this code example from this webiste and do the same with my code, but it didn't worked.

Could you explain to me why? And show me the correct way ?

Community
  • 1
  • 1
Все Едно
  • 746
  • 3
  • 10
  • 24
  • In the example, div was adjacent element to anchor element. Did you try keeping `ul` element adjacent to `li` element instead of making it child of `li` element? – Chitrang Mar 17 '16 at 22:10

2 Answers2

4

Because element with id #hidden is child and not sibling of the element with id #visible. You can use Descendant selector:

#hidden {
  display: none;
}
#visible:hover #hidden {
  display: block;
}
<ul>
  <li id="visible">
    Names
    <ul id="hidden">
      <li>name 1</li>
      <li>name 2</li>
      <li>name 3</li>
      <li>name 4</li>
    </ul>
  </li>

</ul>

References

Adjacent sibling selectors

Alex Char
  • 32,879
  • 9
  • 49
  • 70
0

It doesn't work because you are using the adjacent sibling selector (+). #hidden is a descendent of #visible so no intermediary selector is required:

#hidden {
  display: none;
}

#visible:hover #hidden {
  display: block;
}
<ul>
  <li id="visible">
    Names
    <ul id="hidden">
      <li>name 1</li>
      <li>name 2</li>
      <li>name 3</li>
      <li>name 4</li>
    </ul>
  </li>

</ul>

Your current selector would work for a similar structure to the following, which is obviously invalid:

<ul>
  <li id="visible">
    Names
  </li>
  <ul id="hidden"> /* #hidden is now a sibling of #visible */
      <li>name 1</li>
      <li>name 2</li>
      <li>name 3</li>
      <li>name 4</li>
  </ul>
</ul>
Turnip
  • 35,836
  • 15
  • 89
  • 111