Fix Button CSS for Touchscreen Devices

Why does it happen? (only for technical people):

By default, browsers of touchscreen devices apply the CSS hover rules on the click of a button.

So, when the filter button is tapped on a mobile device, the :hover state is activated along with the plugin-defined select state. That causes both the select state as well as hover state rules to apply on a button.

The select state is removed when you de-select the button; which is its normal expected behavior.

However, the hover state remains until you tap on some another object. This causes the hover styles to be applied and the button’s functionality looks abnormal.

There’s no way to block the hover state from applying on touch devices, however, there’s a nifty CSS hack which will make your button function look normal (like desktop) again.

The Solution

The hack is – To copy the non-hover styles as hover styles for non-desktop devices.

Confusing? Take a look at this example code:

Code when the problem is existing:

.scf-tag-button {
    background: white;
}
.scf-tag-button:hover {
    background: red;
}

With the above code, the button will have a red background color on mobile even after de-selecting.

Code with the solution:

.scf-tag-button {
    background: white;
}
.scf-tag-button:hover {
    background: red;
}
@media (max-width: 991px) {
    .scf-tag-button:hover {
        background: white;
    }
}

Notice the difference between the two?

There’s an extra block of code below the hover styles that specifically target the devices having width lesser than 991px. So, this media rule covers tablets and smartphones, the most common touch devices.

What I did here was, copied all the code (which in this case is just 1 line) from the main .scf-tag-button and pasted it into .scf-tag-button:hover wrapped inside the media rule which targets only smaller devices. So, this media rule won’t affect desktops and things will look visually correct even on mobiles as well now with the fix applied.

Take the media query from the above example, copy all the non-hover styles, paste it inside the hover style for media.

Was this page helpful?