Search code examples
cssflexboxmultiple-columnssticky

two-column sticky flexbox scrolling not working


I'm having trouble getting my flexbox two-column setup to work. Basically I just want the left column to be sticky while scrolling down the right one and then end scrolling at the exact same point. It should also be collapsible as in the example below.

It's supposed to substitute this solutions i made using a regular grid which I'm unfortunately not able use anymore.

You can see my current progress below - I'm not really able to figure out what to do from here - as I'm a rookie I hoped you guys would know.

 
.wrapper {
  display: flex;
  flex-flow: row wrap;
  overflow: auto;
  gap: 2em;
  justify-content: flex-start;
  height: auto;
  font-weight: bold;
  text-align: center;

}

.wrapper > * {
  padding: 10px;
  flex: 1 100%;
}

.aside-1 {
  position: -webkit-sticky;
  position: sticky;
  background: gold;
  height: auto;
  top: 0;
  align-self: flex-start;
}

.aside-2 {
  background: hotpink;
  height: 900px;
  top: 0;
}

@media all and (min-width: 300px) {
  .aside { flex: 1 0 0; }
}
<section class="page-width">


<div class="wrapper">
<aside class="aside aside-1"><img width="100%" src="https://cdn.shopify.com/s/files/1/0044/2852/9698/files/242370040_4238706352865614_2798039132201744827_n.jpg"> Aside 1
</aside>
  <aside class="aside aside-2">
  Aside 2
  </aside>
</div>
</section>

I've checked the forum without really finding what I need and hope that somebody would be able to help me :o) Thanks a million!


Solution

    1. Remove overflow:auto on parent container of sticky element to make stickiness work

    .wrapper {
      display: flex;
      flex-flow: row wrap;
      gap: 2em;
      justify-content: flex-start;
      height: auto;
      font-weight: bold;
      text-align: center;
    }
    
    .wrapper > * {
      padding: 10px;
      flex: 1 100%;
    }
    
    .aside-1 {
      position: -webkit-sticky;
      position: sticky !important;
      background: gold;
      top: 0 !important;
      align-self: flex-start;
    }
    
    .aside-2 {
      background: hotpink;
      height: 900px;
      top: 0;
    }
    
    @media all and (min-width: 300px) {
      .aside { flex: 1 0 0; }
    }
    
    .other-content{
      margin-top: 2rem;
      height: 20rem;
      width: 100%;
      background: red;
      position:sticky;
      top:0;
    }
    <section class="page-width">
    
    
    <div class="wrapper">
    <aside class="aside aside-1"><img width="100%" src="https://cdn.shopify.com/s/files/1/0044/2852/9698/files/242370040_4238706352865614_2798039132201744827_n.jpg"> Aside 1
    </aside>
      <aside class="aside aside-2">
      Aside 2
      </aside>
    </div>
     <div class="divider"></div>
      <div class="other-content"></div>
    </section>