使用CSS网格的位置粘性

ads via CarbonLimited time offer: Get 10 free Adobe Stock images.ads via Carbon

ads via Carbon限时优惠。获得10张免费的Adobe库存图片。广告通过Carbon

Have you ever come across a case where position: sticky isn’t working as expected with a child of a grid container? A few days ago, I was helping a friend in fixing that exact problem and wanted to finally write about it.

你是否遇到过这样的情况:position: sticky ,在网格容器的一个子节点上不能按预期工作?几天前,我正在帮助一个朋友解决这个确切的问题,并想最终写下这个问题。

Introduction

简介

That problem isn’t actually something buggy or wrong. In fact, that’s the effect of a default CSS behavior. Why and how? Let’s see the following example.

这个问题实际上不是什么bug或错误。事实上,那是一个默认的CSS行为的效果。为什么会这样,怎么会这样呢?让我们看看下面的例子。

<div class="wrapper"> <aside></aside> <main></main>
</div>
!----
.wrapper { display: grid; grid-template-columns: 250px minmax(10px, 1fr); grid-gap: 1rem;
}

We have a grid that makes the aside take 250px of width, and the rest of the available space is for the main section. Simple, right?

我们有一个网格,使一旁的宽度占到250px ,其余的可用空间是主部分。很简单,对吗?

Now, we want to add position: sticky to the aside element to make it fixed while scrolling.

现在,我们要在一旁的元素上添加position: sticky ,使其在滚动时固定下来。

aside { position: sticky; top: 0;
}

Oops. It’s not working? Why is that? Let’s find out.

哎呀。它不工作了?这是为什么呢?让我们来找找看。

The default behavior of align-items

的默认行为是align-items

Adding a background to the aside element will show that its height is equal to the main section.

在一旁的元素上添加一个背景,将显示其高度与主部分相等。

This is the default behavior of the align-items property. It defaults to stretch. As a result, a column will stretch in height to match the largest column in the grid.

这是align-items 属性的默认行为。它默认为拉伸。因此,一列的高度将被拉伸,以匹配网格中最大的一列。

Let me show you another example that will help in illustrating the problem better. We have a simple grid container.

让我给你看另一个例子,这将有助于更好地说明这个问题。我们有一个简单的网格容器。

.cards__list { display: grid; grid-template-columns: 1fr 1fr 1fr; grid-gap: 1rem;
}

By default, the cards will stretch to match the largest card (The first one from the right). To override that behavior, we need to change the align-items value to start.

默认情况下,卡片会伸展到与...

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

首页 - Wiki
Copyright © 2011-2024 iteam. Current version is 2.137.3. UTC+08:00, 2024-12-02 23:58
浙ICP备14020137号-1 $访客地图$