The hover
media feature checks if the user's primary input mechanism can conveniently hover over elements. This is key for creating hover effects that don't break the user experience on touch-only devices.
Example 1: Hover Capability Detection
/* styles.css */
/* Apply styles only if the primary input mechanism can hover */
@media (hover: hover) {
.link:hover {
/* Underline link on hover for devices that support it */
text-decoration: underline;
}
}
Explanation
This CSS applies a text underline to a .link
element only when the user hovers over it on a device that supports hovering, like one with a mouse. This prevents the style from being permanently and incorrectly applied on tap-based devices.
Example 2: No Hover Capability
/* styles.css */
/* Apply styles if the primary input mechanism cannot hover */
@media (hover: none) {
.tooltip-trigger .tooltip-text {
/* Make tooltips always visible on devices without hover */
opacity: 1;
visibility: visible;
}
}
Explanation
For devices that cannot hover (like most smartphones), this code makes tooltips (.tooltip-text
) permanently visible. This ensures that information hidden within a hover state is still accessible.
Example 3: Combining Hover with Pointer
/* styles.css */
/* Targets devices that can hover and have a fine pointer */
@media (hover: hover) and (pointer: fine) {
.dropdown-menu {
/* Show dropdown on hover for mouse users */
display: none;
}
.dropdown:hover .dropdown-menu {
display: block;
}
}
Explanation
This example targets the classic desktop experience. A dropdown menu is hidden by default and only appears when a user with a mouse hovers over the .dropdown
container.
Example 4: Alternative Interaction for No-Hover
/* styles.css */
/* Provide a different experience for devices that don't support hover */
@media (hover: none) {
.info-card .details {
/* Ensure details are always expanded on touch devices */
max-height: 500px;
}
}
Explanation
On devices where hover is not the primary interaction method, this CSS ensures that the .details
section within an .info-card
is always expanded, preventing content from being inaccessible.
Example 5: Using any-hover
for Secondary Inputs
/* styles.css */
/* Apply styles if any available input mechanism can hover */
@media (any-hover: hover) {
.subtle-highlight:hover {
/* Add a background color on hover, even if it's a secondary input */
background-color: #f0f0f0;
}
}
Explanation
any-hover
is useful for devices that might have multiple input methods (e.g., a touchscreen laptop with a mouse). This code applies a hover effect if any of the user's input devices support it.