📜 ⬆️ ⬇️

We are looking for hover support on css

image Good day, dear habrakhabrovtsy!

When creating an adaptive version of the site, there are often situations when you need to know whether the browser supports the user hover or not. For example, drop-down when hovering a submenu, or various animations tied to a hover event - all this is needed only on a PC. On touch devices, the behavior of the elements should change. So how to set certain styles only for devices with hover support on css, without forgetting about cross-browser compatibility?

At the beginning I just want to say that there is the Modernizr js-library, which solves this problem. But ... Screwing this library only to determine support for hover, instead of writing a single media query in css is not the best option, in my opinion.

But with media queries is not so simple. Let's see what the options are!
')
1. media (hover)

div{color:red;} @media (hover){ /* hover*/ div{color:green;} } 

This media query will allow you to separately register styles only for devices that support hover. But let's look at browser support: caniuse.com/#feat=css-media-interaction

As you can see, it is not supported by IE and Firefox. Those. our code will perceive these browsers as without hover support. This option does not suit us!

2. media (pointer: coarse)

 div{color:green;} @media (pointer:coarse){ /*touch-*/ div{color:red;} } 

This query works exactly the opposite, i.e. only for touch devices. Support is the same as that of media (hover), but because IE and Firefox are PC browsers - this media query should not work in them anyway.

Such a solution is quite suitable for those cases when you need to register styles specifically for touch devices. But basically, the challenge is to prescribe styles for hover. And this means that you have to first write styles for all browsers, and then drop them in the media query. This not only increases the code, but is also rather inconvenient, since you must duplicate every property changed at a hover event on an element.

3. media (hover) +

Choosing from the above two options, the first is the most attractive. There would be more browser support ...

But, fortunately, we have a variety of media queries that are supported only in certain browsers. The specificity of such support can be found on this site .

So, this code will work only in IE:

 @media (min-width:0\0) {} 

And this media query will only work for Firefox:
 @media (min--moz-device-pixel-ratio:0) {} 

So let's combine all 3 requests!
 div{color:red;} @media (hover) , (min-width:0\0) , (min--moz-device-pixel-ratio:0){ /* hover*/ div{color:green;} } 

The result is a universal media query, triggered by the support of hover.
The request is supported in all major browsers, and as a bonus, it works correctly on Blackberry and in Opera Mini (which was not the case in version 2).

Demo comparison of 3 approaches. Green = hover support:

Source: https://habr.com/ru/post/348502/


All Articles