Activity Breaks CSS :Has() Rules Due To Display:None Not Affecting :Has() Matching
When using cacheComponents and Activity, navigating away from a page hides its content with display:none, but CSS :has() selectors still match hidden elements, causing unintended styles on the new page.
Activity hides inactive page content by applying inline style `display: none`, which does not remove elements from the DOM or adjust their semantic hidden state. CSS :has() operates on DOM structure and does not consider computed styles like display:none, so selectors such as `.parent:has(.element-from-page-a)` continue to match even after navigation.
1. Enable Cache Components in next.config.js
2. Add a :has() CSS rule to your layout that targets page A content
3. Go to page A and then navigate to page B
4. Observe that page B incorrectly applies the :has() rule
Fixing Code Block
// packages/next/src/client/components/activity.tsx
// Modify the Activity container to include the hidden attribute when inactive
// while retaining display:none for backward compatibility.
import * as React from 'react';
interface ActivityProps {
isActive: boolean;
children: React.ReactNode;
}
export function Activity({ isActive, children }: ActivityProps) {
return (
<div
hidden={!isActive}
style={isActive ? undefined : { display: 'none' }}
data-nextjs-activity-hidden={!isActive || undefined}
>
{children}
</div>
);
}
Adding the HTML `hidden` attribute when the Activity is inactive makes the element semantically hidden, allowing developers to write CSS rules like `:has(:not([hidden]))` to correctly exclude hidden content. The `hidden` attribute also triggers the browser's default `display: none`, and retaining the inline `display: none` style ensures consistent behavior across browsers and compatibility with existing code that checks for that style.
Edge Case Audit
This fix may affect existing CSS rules that rely on the absence of the `hidden` attribute or that override `[hidden]` styles differently. The `hidden` attribute removes elements from the accessibility tree, which could impact screen readers if the hidden Activity content should still be accessible. In scenarios with rapid navigation or concurrent route updates, ensure the `isActive` prop is correctly updated to avoid stale hidden states. Rollback suggestion: if this change introduces regressions, revert to using only `display: none` and recommend a workaround such as adding a custom attribute via a wrapper or using CSS `:has(:not([style*="display: none"]))`.