Make flex items overlap

Michael Arrison picture Michael Arrison · May 11, 2017 · Viewed 46.5k times · Source

I'd like to show a horizontal series of a unknown number of playing cards. To do this, they will have to overlap if there are too many. I'm having trouble convincing a flex box to overlap the cards without shrinking them. The example below shrinks the cards. I tried flex-shrink: 0, but then max-width wasn't respected.

Answer

FTWinston picture FTWinston · May 1, 2018

Here's how I'd do this using flexbox.

.cards {
  display: flex;
  align-content: center;
  max-width: 35em;
}

.cardWrapper {
  overflow: hidden;
}

.cardWrapper:last-child, .cardWrapper:hover {
    overflow: visible;
}

.card {
    width: 10em;
    min-width: 10em;
    height: 6em;
    border-radius: 0.5em;
    border: solid #666 1px;
    background-color: #ccc;
    padding: 0.25em;
  
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
<div class="cards">
  <div class="cardWrapper">
    <div class="card">card 1 blah blah blah</div>
  </div>
  <div class="cardWrapper">
    <div class="card">card 2 blah blah blah</div>
  </div>
  <div class="cardWrapper">
    <div class="card">card 3 blah blah blah</div>
  </div>
  <div class="cardWrapper">
    <div class="card">card 4 blah blah blah</div>
  </div>
  <div class="cardWrapper">
    <div class="card">card 5 blah blah blah</div>
  </div>
</div>

Note that technically speaking, the cards aren't overlapping, they're just being clipped. But they look like they're overlapping. The trick is to wrap each card in another element with overflow: hidden.

The wrapping elements are shrunk to fit the available space, and as much of the cards as is possible is displayed in that space.

I include the :hover rule just to show how you could fully display a card from the middle of the "stack", but in a real project I'd probably do this for selected cards instead of hovered ones.