Flexbox are amazing, but sometimes hard to deal with..
Here you have an updated version of JQuery script to target the first-child and last-child of each row using a flex layout :
// Call the function anytime needed, by default on loading and resizing window, see below
function flexboxRowLastChild(){
$(document).ready(function(){
//For each element with class="flexbox-wrapper"
$('.flexbox-wrapper').each(function() {
//Reset at every function call
$(this).children('.flexbox-row-first-child').removeClass('flexbox-row-first-child');
$(this).children('.flexbox-row-last-child').removeClass('flexbox-row-last-child');
//Set :first-child and :last-child (or use css pseudo-element instead)
$(this).children().eq(0).addClass('flexbox-row-first-child');
$(this).children().eq($(this).children().length - 1).addClass('flexbox-row-last-child');
var rowWidth = $(this).children().eq(0).outerWidth(true);
//For counting number of row if needed
var nbrRow = 1;
for (var i = 0; i < $(this).children().length; i++) {
if (rowWidth <= $(this).width()) {
//Sum of every children width (with margin) while it's less than the flexbox-wrapper width
var rowWidth = rowWidth + $(this).children().eq(i+1).outerWidth(true);
} else {
//Set the flexbox-row-first-child and flexbox-row-last-child classes and begin to check for a new row
$(this).children().eq(i-1).addClass('flexbox-row-last-child');
$(this).children().eq(i).addClass('flexbox-row-first-child');
var nbrRow = nbrRow + 1;
var rowWidth = $(this).children().eq(i).outerWidth(true) + $(this).children().eq(i+1).outerWidth(true);
}
}
});
});
}
$(document).ready(function(){
// Call the function on window load
flexboxRowLastChild();
// Call the function on window resize
$(window).resize(function(){
flexboxRowLastChild();
});
});
.flexbox-wrapper {
display: flex;
margin: 0;
padding: 0;
list-style-type: none;
flex-flow: row wrap;
}
.thumbnail {
width: 100px;
height: 100px;
margin: 5px;
background: #ccc;
border: 1px solid #000;
}
.thumbnail.flexbox-row-first-child {
background: #000;
}
.thumbnail.flexbox-row-last-child {
background: #444;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<ul class="flexbox-wrapper">
<li class="thumbnail"></li>
<li class="thumbnail"></li>
<li class="thumbnail"></li>
<li class="thumbnail"></li>
<li class="thumbnail"></li>
<li class="thumbnail"></li>
<li class="thumbnail"></li>
<li class="thumbnail"></li>
<li class="thumbnail"></li>
</ul>