How can I hide items which are not on the first line when using `flex-wrap: wrap` with CSS?

Viewed 419

Consider the following example, where we have a container with display: flex and a bunch of items in it. The container has some kind of width restriction (in this case width: 260px, but it could be just based on its parent or anything else), and it also uses flex-wrap: wrap. This causes some of the items to be placed on a second row (see JSFiddle with this exact code).

<div class="x">
  <div>foo</div>
  <div>foo</div>
  <div>foo</div>
  <div>foo</div>
  <div>foo</div>
  <div>foo</div>
  <div>foo</div>
</div>
.x {
  display: flex;
  width: 260px;
  flex-wrap: wrap;
  border: 3px solid green;
}

.x div {
  border: 5px solid indigo;
  padding: 5px 10px;
}

Now my question is, can I somehow hide only those items which are not on the first (or possibly first two) lines after wrapping? Say that this is a list of tags, and I want to collapse everything but the first few, and then maybe add a :hover that shows the whole list.

The idea is to use flexbox to lay them out nicely with stuff like space-between and flex-grow (or other variants) so that the CSS engine can figure out proper sizes and wrapping, and only then limit which ones should remain visible.

If the hiding-non-first-row part is impossible with pure CSS, but there is a reasonable JS solution, I'd like to see that as well.

0 Answers
Related