首页 > 解决方案 > CSS / HTML如何只显示flexbox的前两行

问题描述

对于一个项目,我需要创建一个搜索栏。搜索结果需要显示在网格中。这些项目应该彼此相邻并且两行高。如果有更多结果,我需要显示一个按钮+32来显示所有结果。

我面临的问题是我不知道如何做到这一点。我使用了 flexbox 和 flex-wrap 以便在新项目不适合上一行时显示在下一行。但我不知道如何只显示前两行。

在此处输入图像描述

.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>

标签: javascripthtmlcss

解决方案


这是一个快速的解决方案,虽然它还没有计算长度。

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>


推荐阅读