Show only the first row of wrapped items that have fluid height in flexbox

Viewed 30

I have wrapper with several items and would like to create fluid columns based on the space available, items that wrap to the second row should be hidden.

In the past I wrote something similar using flexbox and overflow: hidden with only one difference that the items had a fixed height.

In this case the items have a fluid height.

Is this behavior achievable with flexbox ?

Snippet serves as a visual representation of how my items behave

.wrapper {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
  resize: horizontal;
  overflow: auto;
}

.card {
  flex: 1;
  width: 100%;
  min-width: 100px;
  background: red;
  padding: 3px;
}
<div class="wrapper">
  <div class="card">Lipsum</div>
  <div class="card">Longer descriptions</div>
  <div class="card">Longer descriptions <br> foobar</div>
  <div class="card">Small</div>
  <div class="card">Foo</div>
  <div class="card">Barr</div>
</div>

1 Answers

You need to style your cards in two dimensions (columns and rows), which indicates to me that Grid layout is the best tool to use, rather than Flexbox.

Give your first row a template height of auto, and all other rows a height of zero. Set your cards to overflow: hidden to prevent hidden content from showing. You will also need to wrap each card's content in an inner div, to prevent the padding from showing up in hidden cards.

.wrapper {
  display: grid;
  column-gap: 1rem;
  grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
  grid-template-rows: auto;
  grid-auto-rows: 0;
  overflow: auto;
  resize: horizontal;
}

.card {
  background: red;
  overflow: hidden;
}

.card > div {
  padding: 3px;
}
<div class="wrapper">
  <div class="card"><div>Lipsum</div></div>
  <div class="card"><div>Longer descriptions</div></div>
  <div class="card"><div>Longer descriptions <br> foobar</div></div>
  <div class="card"><div>Small</div></div>
  <div class="card"><div>Foo</div></div>
  <div class="card"><div>Barr</div></div>
</div>

Note: Your desired result may be easier to achieve in the future. "nth-row" styling is under consideration for the CSS Grid spec.

Related