CSS网格项目上的粘性位置 [英] sticky position on css grid items

查看:95
本文介绍了CSS网格项目上的粘性位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里查看了其他示例,但是找不到使该功能起作用的示例.我希望页面滚动时侧边栏(部分)保持粘性.位置:如果将其放在导航上,便可以使用粘性,因此我的浏览器def支持它.

I've looked at other examples of this on here but can't find one that makes this work. I want the sidebar (section) to be sticky while the page scrolls. the position: sticky works if I put it on the nav, so my browser def supports it.

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>

推荐答案

您在这里面临的问题是,您的section块消耗了整个高度.因此它不会粘住,因为它太大了.您需要在子节中放置一个子元素,并赋予其粘性属性以使其起作用.根据您的示例,我只是将您的"hi"包裹在div中.

the problem you are facing here is, that your section block consumes the full height. so it won't stick, since it is too large to do so. you would need to put a child element inside your section and give that your sticky attributes, to make it work. based on your example, i simply wrapped your 'hi' inside a div.

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>

这篇关于CSS网格项目上的粘性位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆