brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: @media (hover: hover) so hover styles don't stick on touch screens

Web-Development
~/tips/tip-css-hover-hover-media-query

@media (hover: hover) {

Applies hover effects only on devices that can really hover, not on touch screens.

On a phone, a hover style can stay on after you tap a link, because touch screens emulate hover. A media query keeps the effect for devices that can really hover.

The hover media feature tests whether the primary input mechanism can conveniently hover over elements. MDN lists it as widely available since December 2018. Put the hover effect inside it:

a {
  color: #333;
}

@media (hover: hover) {
  a:hover {
    background: yellow;
  }
}

The value none covers devices where hovering is not possible or not convenient, for example many mobile devices that emulate hover on a long tap, and devices with no primary pointing input. Those never match the block, so the highlight cannot get stuck after a tap. The MDN example takes a gentler route: it keeps a default a:hover rule outside the query and puts the stronger version inside, so every device still gets some hover feedback.

Caveat: the feature looks at the primary input only. A device that has both touch and a mouse is judged by whichever is the primary one, so hover: hover does not guarantee a mouse is present. For that reason, do not hide anything important behind hover. The content or the control has to stay reachable with a tap or the keyboard as well, and a :focus-visible style next to the :hover one is a cheap way to cover keyboard users.

Further reading: MDN: hover media feature

More Web-Development tips ab -n 200 -c 10 https://example.com/ console.assert(items.length > 0, 'cart is empty', items) document.designMode = "on" function save(item) { Save draft All Web-Development tips (67) All topics

Link