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.
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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With