hover on a element and display li elements

I have a problem with hovering on first li or a element to display rest li elements. It's working only if i set hover for ul, but then it's displaying li elements if i hover near the link, since it's block level element.

How can i make work hover on a elemet instead of ul

This is what i have now:

HTML:

<ul>
    <li><a href="#">Link 1</a></li>
    <li><a href="#">Link 2</a></li>
    <li><a href="#">Link 3</a></li>
</ul>

CSS:

li a {
    text-decoration: none;
    display: none;
}

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

ul:hover a {
    display: block;
}

2 answers

  • answered 2017-06-17 19:10 Ori Drori

    Use the general sibling selector ~ to select all the siblings of the 1st list item. You can avoid the block level 100% problem, by floating the list items to the left (width of element is the content's width), and clearing the float to break the line.

    li a {
      text-decoration: none;
      display: none;
    }
    
    li {
      float: left;
      clear: left;
    }
    
    li:first-child a {
      display: block;
    }
    
    li:first-child:hover~li a {
      display: block;
    }
    <ul>
      <li><a href="#">Link 1</a></li>
      <li><a href="#">Link 2</a></li>
      <li><a href="#">Link 3</a></li>
    </ul>

  • answered 2017-06-17 19:10 Daniel H

    set ul to inline-block so hover not triggered when you hover the line(row)

    ul {
      display: inline-block;
      list-style: none;
    }
    
    li a {
      text-decoration: none;
      display: none;
    }
    
    li:first-child a{
      display: inline-block;
    }
    
    li:hover ~ li a {
      display: inline-block;
    }
    <ul>
      <li><a href="#">Link 1</a></li>
      <li><a href="#">Link 2</a></li>
      <li><a href="#">Link 3</a></li>
    </ul>