【问题标题】:sticky position on css grid itemsCSS网格项目上的粘性位置
【发布时间】:2018-11-20 12:44:22
【问题描述】:

我在此处查看了其他示例,但找不到可以实现此功能的示例。我希望侧边栏(部分)在页面滚动时保持粘性。位置:如果我把它放在导航上,sticky 就可以工作,所以我的浏览器 def 支持它。

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,至少我认为你应该这样才能实现你想要的布局
  • 不错,正是我的情况

标签: html css css-position css-grid


【解决方案1】:

您在这里面临的问题是,您的部分块占用了整个高度。所以它不会粘住,因为它太大而不能这样做。您需要在您的部分中放置一个子元素并赋予您的粘性属性,以使其工作。根据您的示例,我只是将您的“嗨”包装在一个 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>

【讨论】:

    【解决方案2】:

    你需要在你想成为sticky的东西上使用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>

    【讨论】:

    • main 中删除background: grey 并查看解决方案的副作用:不再有等高的列,这是CSS Grid 的一个非常重要的好处。
    • 这是一个替代解决方案,但你是对的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-21
    • 2016-10-11
    相关资源
    最近更新 更多