position: sticky; 的奇怪部分

Using position: sticky; is one of those CSS features that’s incredibly useful, seemingly simple, and also, frequently frustrating.

使用position: sticky;是CSS特性之一,它非常有用,看似简单,但也常常令人沮丧。

The premise is simple: you want to be able to scroll your page’s content, but you want something to “stick” at the top (or anywhere). Frequently, this will be some sort of header content that you want to always stay at the top, even as the user scrolls, but it could be any sort of content (and stick edges other than the top, and at any offset).

前提很简单:你希望能够滚动页面的内容,但你希望某些东西在顶部(或任何地方)“粘住”。通常,这将是某种你希望始终保持在顶部的标题内容,即使用户滚动,但它可以是任何类型的内容(并且粘住的边缘可以是顶部以外的地方,且可以在任何偏移量)。

We’ll cover a brief introduction to sticky positioning. We’ll see how it works, and then we’ll look at some common, frustrating ways it can fail. Then we’ll learn exactly how to fix it.

我们将简要介绍粘性定位。我们将看看它是如何工作的,然后我们将查看一些常见的、令人沮丧的失败方式。接着我们将学习如何修复它。

For all the code examples I’ll be using Tailwind, and later, a little React/JSX for looping. I know the Tailwind piece might be controversial to some. But for this post it’ll allow me to show everything in one place, without ever requiring you, dear reader, to toggle between HTML and CSS.

在所有代码示例中,我将使用 Tailwind,稍后会使用一些 React/JSX 进行循环。我知道 Tailwind 这一部分可能对某些人来说有争议。但对于这篇文章,它将让我在一个地方展示所有内容,而不需要你,亲爱的读者,在 HTML 和 CSS 之间切换。

Making Content Stick

让内容粘住

Let’s look at the simplest possible example of sticky positioning.

让我们看一下粘性定位的最简单示例。

<div class="h-[500px] gap-2 overflow-auto"> <div class="flex flex-col gap-2 bg-gray-400 h-[300px]"> <span>Top</span> <span class="mt-auto">Bottom</span> </div> <div class="sticky top-0 h-[100px] bg-red-300 mt-2 grid place-items-center"> <span>I'm sticky!</span> </div> <div class="flex flex-col bg-gray-400 h-[700px] mt-2"> <span>Top</span> <span class="mt-auto">Bottom</span> </div> </div>Code language: HTML, XML (xml)

<div class="h-[500px] gap-2 overflow-auto"> <div class="flex flex-col gap-2 bg-gray-400 h-[300px]"> <span>顶部</span> <span class="mt-auto">底部</span> </div> <div class="sticky top-0 h-[100px] bg-red-300 mt-2 gr...

开通本站会员,查看完整译文。

Accueil - Wiki
Copyright © 2011-2025 iteam. Current version is 2.147.1. UTC+08:00, 2025-11-09 05:13
浙ICP备14020137号-1 $Carte des visiteurs$