当flex项目在列反向时应用nth-child()

Joh*_*rry 8 html css css-selectors css3 flexbox

假设我正在使用一个插件,它按时间顺序在我的页面中添加内容.该插件无法控制添加到页面的项目数量或添加到页面的顺序.

所以,假设在将5个项目添加到页面后,这就是我的HTML的样子:

<div class="flex-container">
  <div class="flex-item">First</div>   <!-- Posted 4 days ago -->
  <div class="flex-item">Second</div>  <!-- Posted 3 days ago -->
  <div class="flex-item">Third</div>   <!-- Posted 2 days ago -->
  <div class="flex-item">Fourth</div>  <!-- Posted 1 day ago -->
  <div class="flex-item">Fifth</div>   <!-- Posted today -->
</div>
Run Code Online (Sandbox Code Playgroud)

我想颠倒顺序,以便首先显示最新的项目,所以我使用:

.flex-container {
  display:flex;
  flex-direction:column-reverse;
}
Run Code Online (Sandbox Code Playgroud)

现在,我的项目按此顺序显示:

Fifth
Fourth
Third
Second
First
Run Code Online (Sandbox Code Playgroud)

现在让我们说我只想在页面上显示最多3个项目.如何使用显示项目的新序列来执行此操作?

如果物品没有用css反转,我可以删除3件物品之后的任何东西:

.flex-item:nth-child(n+4) {
  display:none;
}
Run Code Online (Sandbox Code Playgroud)

但由于它们被颠倒了,上面的CSS正在删除最近的两篇帖子.

TL; DR

css是否能够根据css重新排序的顺序删除子节点,或者我是否需要使用js重新组织html?

Mic*_*l_B 5

如果:nth-child()选择器按预期工作flex-direction: column则...

:nth-last-child()选择应与工作flex-direction: column-reverse

.flex-container {
  display:flex;
  flex-direction:column-reverse;
}

.flex-item:nth-last-child(n+4) {
  background-color: lightgreen;
}
Run Code Online (Sandbox Code Playgroud)
<div class="flex-container">
  <div class="flex-item">First</div><!-- Posted 4 days ago -->
  <div class="flex-item">Second</div><!-- Posted 3 days ago -->
  <div class="flex-item">Third</div><!-- Posted 2 days ago -->
  <div class="flex-item">Fourth</div><!-- Posted 1 day ago -->
  <div class="flex-item">Fifth</div><!-- Posted today -->
</div>
Run Code Online (Sandbox Code Playgroud)

E:nth-child(n)

一个 E 元素,其父元素的第 n 个子元素


E:nth-last-child(n)

一个 E 元素,它的父元素的第 n 个子元素,从最后一个开始计数


来源:https : //www.w3.org/TR/css3-selectors/#selectors