Last active
November 10, 2022 16:17
-
-
Save perjo927/e1f114398fc6fb8538a1412bea800f1a to your computer and use it in GitHub Desktop.
CSS: Support hover only on non-touch devices using media query
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Compiled CSS: | |
*/ | |
a { | |
color: green; | |
} | |
@media not all and (pointer: coarse) { | |
a:hover { | |
color: blue; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@mixin hover-supported { | |
/* | |
* https://developer.mozilla.org/en-US/docs/Web/CSS/@media/pointer | |
* coarse: The primary input mechanism includes a pointing device of limited accuracy. | |
*/ | |
@media not all and (pointer: coarse) { | |
&:hover { | |
@content; | |
} | |
} | |
} | |
a { | |
color:green; | |
@include hover-supported() { | |
color:blue; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// RandomAnchor.tsx | |
import styled, { css } from "styled-components"; | |
import { hoverSupported } from "./CssUtils"; | |
export const RandomAnchor = styled.a` | |
color: green; | |
/* | |
* Only use hover for the browsers we choose to support | |
*/ | |
${hoverSupported(css` | |
&:hover { | |
color: blue; | |
} | |
`)}; | |
`; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Example for React-ts & Styled Components | |
import { css } from "styled-components"; | |
export const hoverSupported = style => css` | |
@media not all and (pointer: coarse) { | |
${style}; | |
} | |
`; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks @aquaductape, duly noted!