Have you needed to apply styling to only touch devices, or only non-touch devices? Well, great news CSS4’s @media (hover: [value])
can come to the rescue in a multitude of ways.
What is CSS4?
For some time we’ve been working with CSS3, which I think is pretty epic, especially when compared to what came before. And CSS4 goes much further, offering super useful functionality to enhance how we interact with webpages. But, for now, we’re only focusing on the media query above, that, for me, is a breath of fresh air, as it vastly simplifies scenarios where I only want to target devices that have specific ways of interacting with the. e.g a touch-only device.
Use-cases for the hover media query
Here are two use-cases to whet the appetite, hopefully, they’ll show the power and flexibility of this awesome new media query?!
Use Case 1: increase spacing between tap targets on touch devices
I’ve had this one a few times, where the links are considered too close, thus reporting accessibility issues. The solution is to give each link (tap target) more spacing on touch devices. In this use case, I’m also using the media query pointer
to detect the type of pointer (none|coarse|fine
) – a perfect use-case for the hover media query:
@media (hover: none) and (pointer: coarse) {
.nav-link {
margin: $nav-link-margin--touch-only;
}
}
Use Case 2: hover effects for devices with hover capability
I was recently building a website where the creative direction required a simple animation that zoomed in on images when hovered over. This featured is intended only for devices that support hover (i.e. mouseover, etc). Here’s a code snippet that increases the scale
of the image element when its parent is in a hovered state :
@media (hover: hover) {
.image-wrap {
overflow: hidden;
> img {
transform: scale(1);
transition: 0.25s ease-in transform;
}
&:hover > img {
transform: scale(1.15);
transition: 2.5s ease-out transform;
}
}
}
As I’ve shown in the two use cases, this is a pretty useful media query and one I will be making a lot of use of. I’m also sure it can be used in conjunction with nest media queries? There is, however, one caveat; there is no support for Internet Explorer and Opera Mobile. But I no longer support IE, unless the client explicitly needs it and frankly cannot support the insanely restrictive Opera Mobile browser (unless the client needs it).
So, there it is, the awesome hover
media query in CSS4. Enjoy using it!
Do you have uses for hover media query?
If you’ve got another use-case for this query, or you’d like help implementing it on your sites’ then please get in touch as we’d love to help make use of this great CSS feature.