Hakeem Almidan

How to Prevent CSS Hover State From Getting stuck on Mobile Browsers

Problem

The CSS hover state often gets stuck on mobile (touch screen) browsers. It would be something like this:

GIF of clicking on link and css hover state getting stuck

Hover state getting stuck on-click on mobile

Solution

Using the ‘hover’ CSS media query, which could be applied either through SCSS or CSS. In the case of SCSS, we’re going to use a mixin.

Here is each solution respectively:

Option 1: SCSS Mixin

The mixin:

@mixin hover-supported {    
    @media (hover: hover) { 
      @content;
    }
}

Example use:

  .example {
    @include hover-supported() {
      &:hover {
        background-color: black;
      }
    }
  }

Option 2: CSS

Example use:

  @media (hover: hover) {
    .example:hover {
      background-color: black;
    }
  }

Explanation

Both examples change the background-color of HTML elements with class example only when they’re hovered-over on non-touch screen devices (or any hover supported device). In short, this applies hover styling on only non-touch screen devices.

PS: I’m not sure how this would act on touch-screen laptops.


Like what you're seeing? Subscribe below to recieve notifications of new posts ⬇️

Promise not to send more than 1 email per month (not counting subscription confirmation email) 👨‍💻


comments powered by Disqus