i’m working on a project using tailwind CSS and React. I’m trying to make sure that hover only works for devices that allow hover.
tailwind.config.js:
/** @type {import('tailwindcss').Config} */
module.exports = {
future: {
hoverOnlyWhenSupported: true,
}...
//Bunch of code
};
I’m using "tailwindcss": "^3.2.4"
Example:
<div className="p-4 bg-red-600 hover:bg-blue-600">Hover Test</div>
I’m expecting "Hover Test" background to turn blue on mobile without hover.
2
Answers
You maybe misunderstanding what
hoverOnlyWhenSupported
does. You can look at the PR this feature was introduced in https://github.com/tailwindlabs/tailwindcss/pull/8394What it essentially does is when
hoverOnlyWhenSupported: true
, the hover features will only be applied when it is applicable, i.e., on Desktops, Laptops or anything with a pointer really.So your expectation of
is wrong. If you want it to appear blue on mobile without hover, you have to do
Breakdown:
bg-blue-600
: As Tailwind is mobile first, this will apply to mobile-like resolutions, so you’ll get blue background without hover as you wanted.md:bg-red-600
: This will apply tomd
screens and beyond. So for non-mobile like screens, you’ll have red background and the hover style will be applied as long as the screens support it.Simple answer, If your use case is just
You don’t have to mess with
hoverOnlyWhenSupported: true
, just try thisWhat happens in the above code ?
As tailwind-css follows
mobile-first
system. Any classes which are not trailed with breakpoint classes likemd:
,sm:
,lg:
and the like is applied to the mobile screen.Therefore:
bg-blue-600
is appliedmd:
screen and above:bg-red-600
is appliedhover:bg-blue-600
is applied to both screens but if can see its affect only in the screen where you can hover using cursor, as you cannot potentionally hover using mobile phones you can’t see it in effect.Further adding to it a statment by @Seth Warburton
When do you use
hoverOnlyWhenSupported: true,
?This is brought up to address issue of:
I’ve noticed that
:hover
in Tailwindcss uses the defaults hover selector which causes ‘stuck’ hover states on mobile.Is there a way to only apply hover styles when supportedExtending to Amit Joki’s answer
Meaning only when there is cursor/pointer in your device such as Desktops, laptops and the like , hover works perfectly, otherwise
hover:
will not take effect and this is to overcome the stuck color change problem as mentioned above in the question link.