jamshid jamshid - 19 days ago 6
CSS Question

Select an element with no children for HOVER

I have the following html code:

<ul class="hover amazing-menu">
<li>
<a href="" class="link">item1</a>
</li>
<li class="parent-item">
<a href="" class="link">item2 <span class="fa fa-caret-down"></span></a>
<ul class="hover sub-menu">
<li class="parent">
<a href="" class="link">sub-item1 <span class="fa fa-caret-right"></span></a>
<ul class="sub-menu2">
<li><a href="link">sub-item11</a></li>
<li><a href="link">sub-item11</a></li>
<li><a href="link">sub-item11</a></li>
<li><a href="link">sub-item11</a></li>
<li><a href="link">sub-item11</a></li>
</ul>
</li>
</ul>
</li>

</ul>


And the following style:

.hover > li.parent-item:hover > ul.sub-menu, .hover > li.parent:hover > ul.sub-menu2{
opacity: 1 !important;}


I want to show sub menu when I hover to element with .parent-item class. It works properly, But when I hover to its children, Sub menu is shown.

Answer

Try to use display: none; and trigger the shown on the shown element :hover.


Look at this example:

ul.sub-menu,
ul.sub-menu2 {
  display: none;
}

a:hover + ul.sub-menu,
a:hover + ul.sub-menu2,
ul.sub-menu:hover,
ul.sub-menu2:hover {
  display: block;
}
        <ul class="hover amazing-menu">
        <li>
            <a href="" class="link">item1</a>
        </li>
        <li class="parent-item">
            <a href="" class="link">item2 <span class="fa fa-caret-down"></span></a>
            <ul class="hover sub-menu">
                <li class="parent">
                    <a href="" class="link">sub-item1 <span class="fa fa-caret-right"></span></a>
                    <ul class="sub-menu2">
                        <li><a href="link">sub-item11</a></li>
                        <li><a href="link">sub-item11</a></li>
                        <li><a href="link">sub-item11</a></li>
                        <li><a href="link">sub-item11</a></li>
                        <li><a href="link">sub-item11</a></li>
                    </ul>
                </li>
            </ul>
        </li>

    </ul>

Fiddle example