Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying nth-child() when flex items are in column-reverse

Let's say I'm using a plugin that's adding content chronologically to my page. The plugin does not give me control of the amount of items added to the page or the order that they are added to the page.

So let's say that this is what my HTML looks like after 5 items have been added to the page:

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

I want to reverse the order so that the most recent item is displayed first so I use:

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

Now, my items are being displayed in this order:

Fifth
Fourth
Third
Second
First

Now let's say that I only want a maximum of 3 items to appear on the page. How can I do that with the new sequence that the items are displayed in?

If the items weren't being reversed with css, I could remove anything after 3 items with this:

.flex-item:nth-child(n+4) {
  display:none;
}

But since they're reversed, the above css is removing the last two most recent posts.

TL;DR

Is css able to remove children based on the sequence that css has reordered them in or will I need to use js to reorganize the html?

like image 449
John R Perry Avatar asked Apr 14 '16 03:04

John R Perry


1 Answers

If the :nth-child() selector works as intended with flex-direction: column, then...

The :nth-last-child() selector should work with flex-direction: column-reverse:

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

.flex-item:nth-last-child(n+4) {
  background-color: lightgreen;
}
<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>

E:nth-child(n)

an E element, the n-th child of its parent


E:nth-last-child(n)

an E element, the n-th child of its parent, counting from the last one


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

like image 184
Michael Benjamin Avatar answered Oct 20 '22 18:10

Michael Benjamin