CSS网格项上的粘性定位

46

我看过这里的其他示例,但找不到使它起作用的示例。我希望侧边栏(部分)在页面滚动时保持粘性。 如果我将position:sticky放在导航上,它就能起作用,因此我的浏览器肯定支持它。

main {
  display: grid;
  grid-template-columns: 20% 55% 25%;
  grid-template-rows: 55px 1fr;
}

nav {
  background: blue;
  grid-row: 1;
  grid-column: 1 / 4;
}

section {
  background: grey;
  grid-column: 1 / 2;
  grid-row: 2;
  position: sticky;
  top: 0;
  left: 0;
}

article {
  background: yellow;
  grid-column: 2 / 4;
}

article p {
  padding-bottom: 1500px;
}
<main>
  <nav></nav>
  <section>
    hi
  </section>
  <article>
    <p>hi</p>
  </article>
</main>


你的侧边栏和导航栏必须固定,而正文内容必须是一个普通的滚动div,至少我认为这样才能实现你想要的布局。 - Dev Man
很好,正是我所处的情况。 - pery mimon
3个回答

45

您需要在想要粘性的元素上使用align-self: start

main {
  display: grid;
  grid-template-columns: 20% 55% 25%;
  grid-template-rows: 55px 1fr;
  background: grey;
}

nav {
  background: blue;
  grid-row: 1;
  grid-column: 1 / 4;
}

section {
  background: grey;
  grid-column: 1 / 2;
  grid-row: 2;
  position: sticky;
  top: 0;
  left: 0;
  align-self: start;
  
}

article {
  background: yellow;
  grid-column: 2 / 4;
}

article p {
  padding-bottom: 1500px;
}
<main>
  <nav></nav>
  <section>
    hi
  </section>
  <article>
    <p>hi</p>
  </article>
</main>


1
main中删除background: grey,并查看您的解决方案的副作用:没有CSS Grid的等高列,这是一个相当重要的好处。 - Frank Conijn - Support Ukraine
这是一个备选方案,但你是正确的。 - James Trenda
我认为显式的“top”定位也是至关重要的。 - djvg

44
您面临的问题是,您的区块占用了整个高度。因此它无法粘住,因为它太大了。您需要在您的区块内放置一个子元素,并将其设置为粘滞性质,以使其起作用。根据您的示例,我只是在一个div中包装了您的“hi”。

main {
  display: grid;
  grid-template-columns: 20% 55% 25%;
  grid-template-rows: 55px 1fr;
}

nav {
  background: blue;
  grid-row: 1;
  grid-column: 1 / 4;
}

section {
  background: grey;
  grid-column: 1 / 2;
  grid-row: 2;
}

section div {
  position: sticky;
  top: 0;
}

article {
  background: yellow;
  grid-column: 2 / 4;
}

article p {
  padding-bottom: 1500px;
}
<main>
  <nav></nav>
  <section>
    <div>
      <p>one</p>
    </div>
  </section>
  <article>
    <p>two</p>
  </article>
</main>


2
请注意,如果这不起作用,请确保您没有带有overflow: hidden的父元素。https://dev59.com/9FcP5IYBdhLWcg3w39o- - keslert

0

更新完整代码

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
main {
  display: grid;
  grid-template-columns: 20% 55% 25%;
  grid-template-rows: 55px 1fr;
}

nav {
  background: blue;
  grid-row: 1;
  grid-column: 1 / 4;
}

section {
  background: grey;
  grid-column: 1 / 2;
  grid-row: 2;
  top: 0;
  left: 0;
}

.fixed-section {
  position: fixed;
  z-index: 1;
  overflow-x: hidden;
}

article {
  background: yellow;
  grid-column: 2 / 4;
}

article p {
  padding-bottom: 1500px;
}
</style>
</head>
<body>

<main>
  <nav></nav>
  <section>
    <div class='fixed-section'>
        <a href="#">Hi 1</a>
    <div>
  </section>
  <article>
    <p>hi</p>
  </article>
</main>
   
</body>
</html> 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接