Feature queries in CSS, using the @media
at-rule, allow you to test for the user's input mechanism and preferences. This enables the creation of more adaptive and user-friendly web interfaces by applying styles based on the capabilities of their device.
pointer
The pointer
media feature is used to test whether the user's primary input mechanism is a pointing device, and if so, how accurate it is. This is crucial for adapting interfaces for touchscreens versus traditional mice.
Example 1: Basic Pointer Detection
/* styles.css */
/* Targets devices with a fine-accuracy pointing device like a mouse */
@media (pointer: fine) {
.button {
/* Make buttons smaller for precise cursor interaction */
padding: 8px 16px;
}
}
Explanation
This code applies specific padding to elements with the class .button
only when the user's device has a fine pointer, such as a mouse. This allows for smaller, more compact UI elements that are still easy to click.
Example 2: Coarse Pointer for Touchscreens
/* styles.css */
/* Targets devices with a coarse-accuracy pointing device like a finger on a touchscreen */
@media (pointer: coarse) {
.button {
/* Increase button size for easier touch interaction */
padding: 15px 25px;
}
}
Explanation
This example targets touch-enabled devices where the primary input is less precise. The CSS increases the padding of .button
elements, making them larger and easier to tap accurately with a finger.
Example 3: No Pointer Device
/* styles.css */
/* Targets devices with no pointing device, like a keyboard-only user */
@media (pointer: none) {
.nav-link {
/* Add a visible focus outline for keyboard navigation */
outline: 2px solid blue;
}
}
Explanation
When a device has no pointing mechanism, navigation is often done via keyboard. This code ensures that .nav-link
elements have a clear visual outline when focused, improving accessibility for keyboard users.
Example 4: Combining Pointer with Other Media Features
/* styles.css */
/* Targets devices with a fine pointer on a wide screen */
@media (pointer: fine) and (min-width: 1024px) {
.gallery-item {
/* Apply a special effect only for mouse users on large screens */
transform: scale(1.05);
}
}
Explanation
This demonstrates how to chain media features. The transform
style for .gallery-item
will only be applied if the device has a fine pointer AND the viewport is at least 1024 pixels wide.
Example 5: Styling for Any Pointer Presence
/* styles.css */
/* This will apply to any device that has some form of pointing device */
@media (pointer: any) {
.interactive-element {
/* Indicates to the user that this element is interactive */
cursor: pointer;
}
}
Explanation
The any-pointer
value can be used to apply styles if any available pointer is present. Here, it changes the cursor to a pointer for .interactive-element
, providing a visual cue of interactivity.