sticky position on css grid items

半腔热情 提交于 2019-12-01 03:24:22
codechella

section needs a height in order for sticky to achieve your desired effect and because of potential quirks with sticky (i.e section would push up over grid-row 1 when you reach the bottom of the page), I'd start section on grid-row 1 rather than 2 along with a wrapper container.

assuming your nav is also sticky, I'd set its z-index so it's on top of the section.

I'd also suggest using @support to use the fixed solutions others have mentioned.

      main {
        display: grid;
        grid-template-columns: 20% 55% 25%;
        grid-template-rows: 55px 1fr;
      }
      
      nav {
        background: blue;
        grid-row: 1;
        grid-column: 1 / 4;
        z-index: 2;
        position: sticky;
        top: 0;
      }
      
      section {
        background: grey;
        grid-column: 1 / 2;
        grid-row: 1;
        position: sticky;
        top: 0;
        left: 0;
        height: 100vh;
      }
      
      section #contents {
        position: relative;
        top: 55px;
      }
      
      article {
        background: yellow;
        grid-column: 2 / 4;
      }

      article p {
        padding-bottom: 1500px;
      }
<main>
  <nav></nav>  
  <section>
    <div id="contents">
      contents
    </div>
  </section>
  <article>
    <p>article</p>
  </article>
</main>

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>
      hi
    </div>
  </section>
  <article>
    <p>hi</p>
  </article>
</main>

Use position: fixed for your section and nav. Maybe, this is similar to what you want:

body {
  margin: 0;
}

nav {
  background: blue;
  height: 80px;
  z-index: 9;
  width: 100%;
  position: fixed;
}

article {
  width: 100%;
  display: grid;
  grid-template-columns: 20vw auto;
}

article p {
  padding-bottom: 1500px;
}

section {
  position: fixed;
  width: 20vw;
  background: grey;
  height: 100%;
  top: 80px;
}

.content {
  margin-top: 80px;
  position: relative;
  grid-column-start: 2;
  background: yellow;
}
<main>
  <nav></nav>
  <section>
    hi
  </section>
  <article>
    <div class="content">
      <p>hi</p>
    </div>
  </article>
</main>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!