Search code examples
csslayoutcss-grid

CSS Grid: Force first 2 DIVs to stack and not overflow-x: auto like the remaining ones


So the big issue I have, is I have NO control of the HTML, just the CSS.

What I have at the moment is a css-grid container with 6 divs inside it. I want the first 2 items to stack 100% of the width, then the remaining ones to overflow-x: auto so on a mobile you can scroll left to right on them.

I've got the scrolling part done okay, but the first two items are also there to scroll, and they're not cards so I want to avoid that.

So I'm only targeting this for mobile screens, but what I have so far:

My HTML (that I can't change)

<div style="container">
  <div>Title</div>
  <div>Sub-title</div>

  <div class="card">CARD 1</div>
  <div class="card">CARD 2</div>
  <div class="card">CARD 3</div>
  <div class="card">CARD 4</div>
</div>

My CSS

@media (max-width: 767px) {
  .container {
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
    display: grid;
    grid-gap: 1.5rem;
    grid-auto-flow: column;
    grid-auto-columns: calc(100% - 3rem);
 }

 .container .card {
    align-items: center;
    display: block;
    justify-content: center;
    width: 100%;
  }
}

Hopefully this image shows what I'm after.

Any help would be greatly appreciated or even if you can let me know if it's possible or not.

Thanks!

enter image description here


Solution

  • Move the card to their own rows and make the other with position:sticky

    .container {
      overflow-x: auto;
      -webkit-overflow-scrolling: touch;
      display: grid;
      grid-gap: 1.5rem;
      grid-auto-flow: column;
      grid-auto-columns: calc(100% - 3rem);
    }
    
    .container .card {
      align-items: center;
      display: block;
      justify-content: center;
      width: 100%;
      height:50px;
      background:red;
      grid-row:3; /* added */
    }
    
    /* added */
    .container :not(.card) {
      position:sticky;
      left:0;
    }
    <div class="container">
      <div>Title</div>
      <div>Sub-title</div>
    
      <div class="card">CARD 1</div>
      <div class="card">CARD 2</div>
      <div class="card">CARD 3</div>
      <div class="card">CARD 4</div>
    </div>