CSS/HTML how to show only the first two lines of a flexbox

Viewed 210

For a project I need to create a search bar. The search results need to be displayed in a grid. The items should be next to each other and two rows high. If there are more results I need to show a button +32 to display all the results.

The problem I am facing is that I have no idea how to accomplish this. I have used flexbox and flex-wrap in order to get new items to be shown in the next line when they don't fit on the previous one. But I don't know how to only display the first two lines.

enter image description here

.container{
  display: flex;
  flex-wrap: wrap;
  background-color: blue;
  max-width: 15rem;
  gap: 1rem;
}

.item{
  background-color: red;
  padding: 0 0.2rem;
}
<div class="container">
  <div class="item">
    <p>Hello</p>
  </div>
  <div class="item">
    <p>Helllooo</p>
  </div>
  <div class="item">
    <p>Hel</p>
  </div>
  <div class="item">
    <p>Hello</p>
  </div>
  <div class="item">
    <p>Test</p>
  </div>
  <div class="item">
    <p>For</p>
  </div>
  <div class="item">
    <p>Hello</p>
  </div>
  <div class="item">
    <p>Hello</p>
  </div>
  <div class="item">
    <p>Helllooo</p>
  </div>
  <div class="item">
    <p>Hel</p>
  </div>
  <div class="item">
    <p>Hello</p>
  </div>
</div>

1 Answers

Here is a quick solution, although it doesn't calculate the length yet.

items = ["Helooo","Testing","Holaaaa","Hiiii","Hello","Greetings fine sir","Welcome","Bonjour","Oi you there"];

let limit = 5; // You will need to calculate this somehow

function display(limit){
    document.getElementById("searchContainer").innerHTML = "";
    for (let item of items.slice(0,limit)){
        document.getElementById("searchContainer").innerHTML += `<div class=item>${item}</div>`;
    }
    if (items.length > limit){
        document.getElementById("searchContainer").innerHTML += `<div class=item onclick="display(${items.length})">+${items.length-limit}</div>`;
    }
}

display(limit);
.container{
  display: flex;
  flex-wrap: wrap;
  background-color: whitesmoke;
  max-width: 15rem;
  gap: 1rem;
}

.item{
  background-color: rgb(100,100,200);
  padding: 0 0.2rem;
  border-radius: 2px;
}
<div class=container id=searchContainer>
</div>

Related