scroll-behavior: smooth完全失效求助:已设overflow-y: scroll仍无效
scroll-behavior: smooth Not Working on Custom Container Got it, let's break down why your smooth scroll isn't kicking in, then fix it step by step.
Why It's Failing
The default <a href="#id"> anchor links trigger scrolling on the entire document (the <html>/<body> elements), not your custom #container scrollable area. Even though you added scroll-behavior: smooth to #container, the scroll event never fires on that container—so the smooth effect has nothing to attach to.
Solution 1: Pure CSS Adjustment (Layout-Dependent)
If you can make #container the only scrollable element on the page, you can trick the default anchor behavior to target it. Here's how:
- Disable scrolling on the root elements:
html, body { height: 100%; margin: 0; overflow: hidden; }
- Ensure
#containerfills the viewport to become the main scroll area:
#container { height: 100vh; overflow-y: scroll; scroll-behavior: smooth; }
- Keep your existing CSS for
.topTab,.pg, andaunchanged.
With this setup, clicking anchor links will scroll the #container (since it's the only scrollable context) and the smooth behavior will work as expected.
Solution 2: JavaScript Approach (More Flexible)
If you can't modify the root scroll behavior (e.g., your page has other scrollable sections), use JS to manually trigger smooth scrolling on the container. Here's the code:
First, add a class to your anchor links for easier targeting:
<div class="topTab"> <li><a href="#1" class="container-anchor">1</a></li> <li><a href="#2" class="container-anchor">2</a></li> <li><a href="#3" class="container-anchor">3</a></li> </div> <div id="container"> <div id="1" class="pg">1</div> <div id="2" class="pg">2</div> <div id="3" class="pg">3</div> </div>
Then add this JavaScript:
const anchors = document.querySelectorAll('.container-anchor'); const container = document.getElementById('container'); anchors.forEach(anchor => { anchor.addEventListener('click', (e) => { // Stop default document scroll e.preventDefault(); // Get target element from the anchor's href const targetId = anchor.getAttribute('href'); const targetElement = document.querySelector(targetId); if (targetElement) { // Smooth scroll the container to the target container.scrollTo({ top: targetElement.offsetTop, behavior: 'smooth' }); } }); });
This code intercepts anchor clicks, blocks the default document scroll, and tells your #container to smoothly scroll to the target element instead.
Quick Tips
- For better HTML compliance, avoid IDs starting with numbers (swap
id="1"forid="pg1"—most browsers handle numeric IDs, but it's not standard). scroll-behavior: smoothworks in all major modern browsers; if you need older browser support, add a polyfill for the JS approach.
内容的提问来源于stack exchange,提问作者James Lee




