Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sticky position on css grid items

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>
like image 690
totalnoob Avatar asked Jun 11 '18 09:06

totalnoob


People also ask

Can a grid item be sticky?

If you've ever tried to put a sticky item in a grid layout and watched the item scroll away with the rest of the content, you might have come to the conclusion that position: sticky doesn't work with CSS Grid. Fear not! It is possible to get these two layout concepts working together.

How do I make my grid sticky?

You need to use align-self: start on the thing you want to be sticky . Delete the background: grey from main and see the side effect of your solution: no more equal-height columns, a quite important benefit of CSS Grid. It's an alternate solution, but you're right.

How do you use sticky position in CSS?

CSS Demo: position To see the effect of sticky positioning, select the position: sticky option and scroll this container. The element will scroll along with its container, until it is at the top of the container (or reaches the offset specified in top ), and will then stop scrolling, so it stays visible.


1 Answers

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>
like image 178
honk31 Avatar answered Oct 04 '22 16:10

honk31