React 與 Tailwind CSS 中的 CSS scroll-state() 使用教學
Mastering CSS scroll‑state() in React & Tailwind
CSS scroll-state() 可根據元素或視口的捲動狀態套用樣式,讓 React 元件以 CSS 回應捲動,而無需用 JavaScript 偵測捲動事件。Tailwind CSS 預設沒有相關工具類別,但可透過自訂外掛擴充。使用時應避免複雜樣式,並為尚未支援的瀏覽器提供後備樣式。
What Is scroll‑state() and Why It Matters
CSS scroll‑state() is a media query‑like feature that lets you apply styles based on the current scrolling activity of an element or the viewport. Unlike the traditional :hover or :focus pseudo‑classes, scroll‑state() can detect whether the user is actively scrolling, has stopped, or has scrolled to the top or bottom. This opens up new UI possibilities such as:
- Showing a “Back to top” button only after the user has scrolled past a threshold.
- Changing a header’s background color when the page is being scrolled.
- Triggering lazy‑load animations when the user stops scrolling.
Because the feature is purely CSS, it keeps JavaScript logic minimal and can be leveraged directly in React components.
How to Write a scroll‑state() Query
The syntax follows the same pattern as other media queries:
@media (scroll-state: scrolling) { … }
@media (scroll-state: idle) { … }
@media (scroll-state: top) { … }
@media (scroll-state: bottom) { … }
You can also combine conditions with and:
@media (scroll-state: scrolling) and (orientation: portrait) { … }
These queries are evaluated against the element they are applied to. When used on :root, they refer to the viewport.
Using scroll‑state() in a React Component
Let’s create a simple header that changes its background color while scrolling.
// Header.tsx
import React from 'react';
export default function Header() {
return (
<header className="fixed w-full z-10 transition-colors duration-300">
<h1 className="text-xl p-4">My Site</h1>
</header>
);
}
Add the CSS that reacts to the scrolling state:
/* styles.css */
@media (scroll-state: scrolling) {
header {
background-color: rgba(255, 255, 255, 0.8);
}
}
@media (scroll-state: idle) {
header {
background-color: transparent;
}
}
Because the CSS is global, it automatically applies to the Header component. No JavaScript is required to detect the scroll event.
Integrating with Tailwind CSS
Tailwind does not ship with scroll‑state() utilities out of the box, but you can extend it. Add a custom plugin in tailwind.config.js:
// tailwind.config.js
module.exports = {
// …
plugins: [
function ({ addVariant, e }) {
addVariant('scroll-state-scrolling', ({ modifySelectors, separator }) => {
modifySelectors(({ className }) => {
return `.scroll-state-scrolling\\:${e(className)}`;
});
});
}
]
}
Now you can use the variant in your JSX:
<header className="fixed w-full z-10 transition-colors duration-300
bg-transparent scroll-state-scrolling:bg-white/80">
<h1 className="text-xl p-4">My Site</h1>
</header>
The scroll-state-scrolling: prefix tells Tailwind to apply the style only when the element is being scrolled.
Performance Considerations
- Avoid heavy CSS in scroll‑state queries – The browser must repaint the element whenever the state changes. Keep styles simple (e.g., background colors, transforms).
-
Prefer
will-changefor animations – If you animate properties that depend on scroll state, usewill-changeto hint the compositor thread. -
Use
@media (scroll-state: idle)sparingly – Idle state fires after scrolling stops, which can trigger expensive recalculations if you’re running JavaScript in the same event loop. -
Test on mobile – Some mobile browsers may not support scroll‑state() yet. Use
@supportsto provide fallbacks:
@supports not (scroll-state: scrolling) {
/* fallback styles */
}
Combining scroll‑state() with Intersection Observer
For more complex interactions, pair scroll‑state() with the Intersection Observer API. For example, you can trigger a CSS animation only when an element is visible and the user is not scrolling:
// In a component
useEffect(() => {
const observer = new IntersectionObserver(
entries => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('visible');
} else {
entry.target.classList.remove('visible');
}
});
},
{ threshold: 0.5 }
);
document.querySelectorAll('.animate-on-visible').forEach(el => observer.observe(el));
}, []);
Then in CSS:
.animate-on-visible {
opacity: 0;
transition: opacity 0.3s;
}
@media (scroll-state: idle) {
.animate-on-visible.visible {
opacity: 1;
}
}
Accessibility Tips
- Avoid flashing content – Rapid changes triggered by scroll‑state() can be disorienting. Keep transitions smooth.
- Provide keyboard alternatives – If you hide elements while scrolling, ensure they remain reachable via keyboard navigation.
Conclusion
CSS scroll‑state() offers a clean, declarative way to adapt UI based on scrolling activity. In React, it keeps component logic minimal, and when combined with Tailwind’s utility‑first approach, you can write expressive, maintainable code. Keep performance in mind by limiting complex styles and testing across browsers.
FAQ
1. Does scroll‑state() work in all modern browsers?
Scroll‑state() is supported in recent versions of Chrome, Edge, and Safari. Firefox support is pending. Always check the latest compatibility on caniuse.com.
2. Can I use scroll‑state() on an element that isn’t scrollable?
Yes. When applied to :root, it reflects the viewport’s scroll state. For non‑scrollable elements, the query will never match unless the element itself can scroll (e.g., overflow: auto).
3. How do I provide a fallback for browsers that don’t support scroll‑state()?
Wrap your CSS in an @supports rule:
@supports not (scroll-state: scrolling) {
/* fallback styles here */
}
This ensures graceful degradation for unsupported browsers.
This post was drafted with AI assistance.
來源:DEV Community · dev.to