I want to make a menu-item which:
- Reveals a drop-down submenu, when the item is hovered (using a mouse) or touched (using a touch-screen).
- Lets you click on a link in the submenu, while the submenu is visible
- Closes the submenu (without clicking on a link), if you move the mouse outside the submenu (using a mouse) or touch anywhere outside the submenu (using a touch-screen).
Here's my HTML fragment (to be enclosed within HTML5 <body>
element):
<div class="menuitem">
Drop-down menu item
<br />
<ul class="submenu">
<li><a href="foo.html">First sub-item</a></li>
<li><a href="bar.html">Second sub-item</a></li>
</ul>
</div>
<h1>Heading</h1>
<p>Lorem ipsum.</p>
Here's my CSS:
div.menuitem
{
height: 3em;
}
div.menuitem:hover ul.submenu
{
left: auto;
}
ul.submenu
{
left: -999em;
z-index: 1;
margin: 0;
position: absolute;
width: 10em;
list-style: none;
padding: 0;
line-height: 1.6;
background-color: Black;
}
ul.submenu a
{
color: White;
}
The important part of the CSS is:
ul.submenu {left: -999em;
makes theul.submenu
invisible, off to the left of the screendiv.menuitem:hover ul.submenu { left: auto;
makes theul.submenu
visible (not off to the left of the screen) when the div is hovered.
Here is a demo.
This seems to work correctly (e.g. the submenu items become visible) when I touch it using the browser on an Android tablet.
Is the above code sufficient? If not then in what circumstance would it malfunction?
IMO, on a touch screen the browser is (or at least, all browsers that I have tried are) synthesizing a 'hover' event (and applying the hover style) when it detects a user touch.
Other solutions that I've seen on the 'net seem much more complicated than this, for example:
- Handling Hover Events on a Touch Screen uses JavaScript
- Click function for
:hover
states on touch devices suggests that it's necessary to use:focus
or:active
, because:hover
doesn't work.
Furthermore the Mozilla help says not to rely on hover:
On touch screens :hover is problematic or impossible. The :hover pseudo-class never matches, or matches for a short moment after touching an element. As touchscreen devices are very common, it is important for web developer not to have content accessible only when hovering over it, as this content would be hidden for users of such devices.
However, this code I posted seems to work, so I don't know what's wrong with it or how to fix it.
Articles like How to deal with :hover on touch screen devices and iOS has a :hover
problem suggest that :hover
is supported on touch screens but that it causes "double tap behavior on touch screens".
Am I right in thinking that:
:hover
is reliably synthesized on touch screen devices- I am expecting/requiring the user to double-touch (once to open the submenu and a second time to touch a link inside the submenu) and therefore "double tap behavior" isn't a problem.