Reputation: 39
I want to perform an action that when I hover on the image, the drop-down menu will be shown.
The below code works fine.
HTML, CSS:
.menu {
position: relative;
display: inline-block;
}
.menu .dropdown-menu {
position: absolute;
top: 100%;
left: 0;
margin: 0;
display: none;
}
.menu:hover .dropdown-menu {
display: block;
}
<div class="menu">
<img src="http://sharpinsurance.ca/images/menu-collapse.png" id="menu-icon" alt="menu-icon" />
<ul class="dropdown-menu">
<li><a href="#home">Account</a>
</li>
</ul>
</div>
My question is why I can't use #menu-icon:hover
to perform the action?
#menu-icon:hover .dropdown-menu {
display:block;
}
Upvotes: 2
Views: 57
Reputation: 71
Just like to add that using hover as the only way to show a menu is not very user-friendly. If you are not using a mouse it's not possible to interact with the menu. Also even if you are using a mouse it can be hard to interact since the menu will close as soon as the mouse is not actually hovering.
I would suggest trying something else or maybe add some JavaScript to improve the accessibility.
Upvotes: 0
Reputation: 115009
Based on this structure:
<div class="menu">
<img src="icon.jpg" id="menu-icon" alt="menu-icon"></img>
<ul class="dropdown-menu">
<li><a href="#home">Account</a></li>
</ul>
</div>
The selector / combinator you are using is incorrect and should be:
#menu-icon:hover + .dropdown-menu {
display:block;
}
The space between .menu-icon
and .dropdown-menu
you are using assumes that the menu is a child of the image which it isn't.
The menu is the next sibling and is selected with the +
combinator.
The 30 CSS Selectors You Must Memorize
Upvotes: 4