Mobile Safari (iOS) has no concept of hover, in general. Obviously, with touch devices, you can’t have this feature. The screen needs to be touched for it to detect any user interaction. That makes sense. And with that in mind, it would be OK to say that we can ignore all :hover CSS rules, because quite simply, they should not be valid on touch devices. However, in reality, what actually happens is that when you touch something on an iOS device, it first trigger the “hover” state (any :hover selector CSS rules would get applied) and then it triggers the “click” state (any click handlers would run).

The Problem

This is where you can run into issues sometimes if you are not careful with your CSS rules. Let’s assume you have a CSS rule that would change the color of a link on hover. e.g.


Nothing wrong there, obviously. However, on an iOS device, when you click the above link and navigate away to the next page and then hit the browsers’ back button, when you come back on this screen, you will see the above link is still in hover state (i.e. color #f6efd8 applied to it). This happens because the click on the link applied the hover CSS to it and then the back button really does not render the page again. It simply reloads the page from cache in whatever state it was in.

The Solution

There can be several ways of dealing this, I think. However, the quickest solution is simply to not let iOS pick up the :hover selector CSS rules. Now, that can be really straight-forward if you are using Modernizr. Modernizr detects HTML5 and CSS features in a browser and adds certain classes to the “html” element of the DOM. This lets us write our CSS selectively. So, in this particular situation, Modernizr would add a class called “touch” if it was a touch enabled device and a class called “no-touch” if it was not a touch enabled device. With that information, all we need to do is change our :hover CSS rule to look like this :-

[css].no-touch a:hover{color:#f6efd8;}[/css]

And that’s it. The hover selector won’t get picked up anymore.

If you don’t want to use Modernizr (althought I would recommend it totally!), you can use media queries to solve this problem. Here is how the CSS would look like for iPhone detection

[css]@media only screen and (max-device-width: 480px){

If you think this can be handled in any other way, let me know.

Tagged with:  

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

© 2011 Anuj Gakhar