为什么在Tailwind CSS中滚动平滑不起作用



所以,我有这个代码:

<div className="bg-black font-serif pl-20 grid text-white !scroll-smooth">
<Head>
<title>MinimDays | Ultimate minimalism</title>
<link rel="icon" href="/plant.ico" className="fill-white" />
</Head>
<section id="home">
<div className="flex">
<span className="pt-72 mr-[400px]">
<h1 className="text-3xl ">MinimDays | Ultimate minimalism</h1>
<Link href="#about"><a className="text-lg hover:text-gray-400">About</a></Link> |
<Link href="#contactus"><a className="text-lg hover:text-gray-400"> Contact Us</a></Link>
</span>
<picture>
<img src="/photo.jpg" alt="photo" className="h-[480px] w-[320px] mt-[80px] rounded-xl border-white border-4"/>
</picture>
</div>
</section>
<section id="about" className="mt-20">
<h1 className="text-3xl mb-5">About Us</h1>
<hr className="mb-5"/>
<p className="text-lg">I like the idea of digital minimalism, but apps that satisfy this category are usually paid <br /> or have a free tier which is highly limited, so I said SCREW IT, <br /> and created my own! </p>
</section>
</div>

并且滚动动画不起作用。我试过Firefox开发版和Chrome,但似乎没有任何帮助。有什么建议吗?

您需要为html元素添加平滑滚动。因此,将其添加到您的主css文件中:

html {
scroll-behavior: smooth;
}

在我组装的HTML版本中,我通过上面的更改成功地使用了您的示例代码。

我还没有在Next.js中测试过它,但请注意,<Link />用于页面之间的导航。不确定这是否会导致页面中的链接出现问题。

MDN平滑滚动文档:

在根元素上指定此属性时,它将应用于视口。在主体元素上指定的此属性不会传播到视口。

https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-behavior

我使用的是Next.js中的Link组件,它不能使用滚动平滑,只能使用标记。