Search code examples
htmlcssflexbox

Horizontal list of items: the next to last item is centered, while the last item takes all of the remaining space


I'm building a horizontal list of items:

example of a horizontal list of items

Once scrolled to the end of the list, the second last item needs to be in center, and the last item takes all of the remaining space after it.

example of a horizontal list of items where second last item is centered (green), and the last item takes all of the remaining space

I've had a success in making the list of items, but not sure what's the best way to implement the desired behaviour of having second last item centered and last item taking remaining space. Here is my current code:

I would appreciate any help or advice for guiding me in the right direction. Thank you!

/* layout */

.container {
  display: flex;
  overflow-x: auto;
  gap: 21px;
}

.item {
  min-width: 212px;
  height: 254px;
}


/* visuals */

.container {
  padding-left: 11px;
}

.item {
  background: #D9D9D9;
}

.item.green {
  background: #099F9F;
}

.item.red {
  background: #FF6262;
}
<div class="container">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item green"></div>
  <div class="item red"></div>
</div>


Solution

  • You can define the width as calc((100% - item_wdith - 2*gap)/2)

    .container {
      display: flex;
      overflow-x: auto;
      padding-left: 10px;
      gap: 20px;
    }
    
    .item {
      width: 220px;
      flex-shrink: 0;
      height: 254px;
      background: #D9D9D9;
    }
    
    .item.green {
      background: #099F9F;
    }
    
    .item.red {
      background: #FF6262;
      width: calc((100% - 220px - 2*20px)/2);
    }
    
    /* to illustrate the center */
    html {
      background: linear-gradient(red 0 0) 50%/2px 100% no-repeat;
      min-height: 100%;
    }
    <div class="container">
      <div class="item"></div>
      <div class="item"></div>
      <div class="item"></div>
      <div class="item"></div>
      <div class="item"></div>
      <div class="item"></div>
      <div class="item"></div>
      <div class="item"></div>
      <div class="item green"></div>
      <div class="item red"></div>
    </div>