【问题标题】:How can I conceal partial rows in a flex column using CSS?如何使用 CSS 隐藏 flex 列中的部分行?
【发布时间】:2020-05-27 04:12:28
【问题描述】:

这在标题中很难解释。我有一个 div,它显示列的 flex 和 flex-direction,其中有很多行:

<div class="flex column">
    <div class="row">Content of row</div>
    <div class="row">Content of row</div>
    <div class="row">Content of row</div>
    <div class="row">Content of row</div>
    <div class="row">Content of row</div>
    //etc
</div>

每行高 20 像素,容器隐藏了溢出。除非容器的高度是 20 的倍数,否则会留下部分可见的行。

我想要完成的是让 CSS 自动使行高足够高,以使最后一个半可见行不再可见,并且以 px 为单位的新行高精确地划分为父容器。

这可以用纯 CSS 完成吗?

我可以接受的另一个选项是 CSS 自动隐藏现在部分可见的最后一行

这是问题的代码:https://codepen.io/random33443/pen/WNQBQOy

【问题讨论】:

  • 请提供一个最小的例子作为我们可以玩的 sn-p。那会容易得多。 :)
  • 是否总是只有一个部分和/或隐藏的行?我假设了一个灵活的高度场景。不过,答案可能不是。一点 JavaScript 可以让你的容器高度变圆或隐藏行。
  • 我添加了一个codepen。谢谢
  • CSS 真的无法做到这一点,javascript 可以:fork codepen.io/gc-nomade/pen/rNOgOKB

标签: html css flexbox


【解决方案1】:

您可以依赖换行功能,您的元素会自动移动到无人能看到的另一列。

调整以下示例的大小并查看:

.flex-column {
  display:flex;
  flex-direction:column;
  flex-wrap:wrap; /* this is important */
  height:200px;
  overflow:hidden; /* this one too */
  resize:vertical;
  border:1px solid red;
}
.flex-column *{
  height:25px;
  flex-shrink:0;
  border:2px solid green;
  width:100%; /* and especially this one */
  box-sizing:border-box;
}
<div class="flex-column">
    <div class="row">Content of row</div>
    <div class="row">Content of row</div>
    <div class="row">Content of row</div>
    <div class="row">Content of row</div>
    <div class="row">Content of row</div>
</div>

【讨论】:

  • 这很巧妙。
【解决方案2】:

如果您为容器设置自动高度,它会调整大小以适应您添加的行数。如果您的容器具有固定高度,您可以使用:last-of-type 定位并隐藏您的最后一行:

.flex.column{
   display:flex;
   flex-direction: column;
   border: solid 1px #aa2233;
}

.row{
  height: 20px;
  border: solid 1px #333;
  box-sizing:border-box;
}

.sized{
   height: 110px;
   overflow:hidden;
}

.sized .row:last-of-type{
  display:none;
}
<h2>Auto Height</h2>
<div class="flex column">
    <div class="row">Content of row</div>
    <div class="row">Content of row</div>
    <div class="row">Content of row</div>
    <div class="row">Content of row</div>
    <div class="row">Content of row</div>
    <div class="row">Content of row</div>
</div>

<h2>Fixed Height</h2>
<div class="flex column sized">
    <div class="row">Content of row</div>
    <div class="row">Content of row</div>
    <div class="row">Content of row</div>
    <div class="row">Content of row</div>
    <div class="row">Content of row</div>
    <div class="row">Content of row</div>
</div>

【讨论】:

  • 谢谢,但这并不能完全解决它,因为即使最后一行不需要隐藏,它也会隐藏最后一行 - 例如如果高度为 100 像素,行高为 20 像素,则行完全适合容器。
  • @FachtnaSimi 我认为没有 javascript 就无法做到这一点。您需要能够在动态高度上使用除法。
猜你喜欢
  • 1970-01-01
  • 2021-02-14
  • 2015-03-29
  • 2019-04-15
  • 1970-01-01
  • 2017-05-04
  • 1970-01-01
  • 1970-01-01
  • 2012-03-30
相关资源
最近更新 更多