Potentially Coming to a Browser :near() You

Introduction to :near()
The :near() pseudo-class is a proposed CSS feature that would allow developers to style elements based on the proximity of the user's pointer. For example, using button:near(3rem) would apply styles when the pointer is within 3rem of the button. Although not yet supported in browsers, understanding its potential can enhance user experience significantly.
Simulating :near() Functionality
While waiting for browser support, you can simulate the :near() effect using CSS and JavaScript. For instance, create a button that appears when the user hovers over a container with padding. This can be achieved with the following CSS:
#simulate-near {
padding: 3rem;
}
button {
content-visibility: hidden;
animation: 1ms show-content;
contain-intrinsic-size: auto none;
}
This code ensures that the button remains focusable and maintains its space even when hidden, allowing for a smoother user interaction.
Accessibility Considerations
When using hidden elements, it's crucial to maintain accessibility. Avoid using display: none or visibility: hidden, as these methods remove elements from the accessibility tree. Instead, utilize content-visibility: hidden combined with the hidden attribute to ensure elements remain accessible. For example:
<button hidden="until-found">Share</button>
This approach allows the button to be found by assistive technologies while still being visually hidden until the user is near it.
Advanced Use Cases
The concept of :near() can extend beyond simple visual effects. For instance, consider integrating it with the Speculation Rules API to prefetch resources when the user is near a link. This could significantly enhance loading times and user experience. Additionally, the Interest Invoker API could leverage proximity to prevent accidental dismissals of overlays, improving interaction fluidity.
Actionable Next Steps
- Experiment with simulating :near() in your projects using the provided CSS and HTML techniques.
- Ensure that any hidden elements are accessible by implementing the recommended accessibility practices.
- Keep an eye on browser updates for the official support of :near() and explore how it can be integrated into your workflows.
- Consider how proximity-based interactions could enhance your current user interface designs.
Get your personalized feed
Trace curates the best articles, videos, and discussions based on your interests and role. Stop doom-scrolling, start learning.
Try Trace free