
CSS Hover Media Query
A progressively enhanced "hover" media query.
Visitor stats

Code stats

About
Detailed info about the Hover CSS media feature can be found on the MDN website.
This CSS media feature is implemented and supported in almost all modern browsers and works as expected.
The modern browsers include Chrome, Opera, Safari, Edge, Brave, Vivaldi, etc.
Internet Explorer and Firefox (prior v.64) do not understand this media feature and therefore will simply ignore all rules inside the query.
Details
The Hover Media Query module provides means to progressively enhance the CSS hover state by providing a unified set of media queries which target all browsers:
Examples
The following example shows how to use the Hover Media Query and target all browsers which support the hover CSS media query.
The following example targets also browsers which do not support it (such as IE and Firefox prior v.64).
@media (-ms-high-contrast: none), (-ms-high-contrast: active), (-moz-touch-enabled: 0), (hover: hover) {
.element:hover {
color: lavender;
}
}
The following example shows how to use the Hover Media Query and target all browsers which support the hover media query but do not support the CSS hover state (such as mobile browsers which are usually used without a pointer device).
@media (hover: none) {
.element {
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
.element:active {
color: lavender;
}
}
Bonus 1: SCSS mixin
If your environment supports the SCSS language, you can use the SCSS provided here:
First define the SCSS mixin:
@mixin hover {
@media (hover: none) {
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
&:active {
@content;
}
}
@media (-ms-high-contrast: none), (-ms-high-contrast: active), (-moz-touch-enabled: 0), (hover: hover) {
&:hover {
@content;
}
}
}
Or import it:
@import 'hover-media-query/hover.scss';
And then use it wherever appropriate:
.button {
@include hover {
color: lavender;
}
}
Bonus 2: PostCSS custom media queries
If your environment is configured to use the PostCSS postprocessor, you can use the custom PostCSS media queries.
In order to to so you need to install and configure the PostCSS Custom Media plugin
First define the custom media queries:
@custom-media --hover (-ms-high-contrast: none), (-ms-high-contrast: active), (-moz-touch-enabled: 0), (hover: hover);
@custom-media --no-hover (hover: none);
Or import them:
@import 'hover-media-query/hover.css';
And then use them wherever appropriate:
@media (--hover) {
.button:hover {
color: lavender;
}
}
@media (--no-hover) {
.button {
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
.button:active {
color: rebeccapurple;
}
}
LICENSE
MIT
Connect with me: