How about a PURE CSS solution:
We can use a series of media queries to achieve this. With the media queries in place we can target the last item in each row and change its color.
Now this may sound like a cumbersome task, but if you are using a preprocessor such as LESS - this isn't such a difficult or error-prone task.
All we need to do is set up a few variables in the LESS mixin according to our needs - and we get the exact layout that we're after. Take a look....
CODEPEN (Resize to see this in action)
Usage is simple - just call the LESS mixin like so:
.box-layout(boxItemList,li,100px,120px,2,7,20px);
Where the mixin takes 7 parameters:
1) The list selector
2) The item selector
3) item width
4) item-height
5) min cols
6) max-cols
7) margin
We can change these parameters to whatever we need and we'll get the layout we need
Here's CSS (LESS) code:
.box-layout(@list-selector,@item-selector, @item-width, @item-height, @min-cols, @max-cols, @margin)
{
@item-with-margin: (@item-width + @margin);
@layout-width: (@min-cols * @item-with-margin - @margin);
@next-layout-width: (@layout-width + @item-with-margin);
@layout-max-width: (@max-cols * @item-with-margin - @margin);
@layout-min-width: (@min-cols * @item-with-margin - @margin);
@list: ~" `'\n'`.@{list-selector}";
@item: ~" `'\n'`@{item-selector}";
@{list} {
display: block;
margin: 0 auto;
list-style: none;
border: 5px solid aqua;
overflow: auto;
padding:0;
color: white;
min-width: @layout-min-width;
max-width: @layout-max-width;
}
@{item} {
height: @item-height;
width: @item-width;
margin: 0 @margin 32px 0;
background: tomato;
float:left;
}
@media (max-width:@layout-min-width) {
@{list} {
width: @item-width;
min-width: @item-width;
}
@{item} {
margin-right:0;
background: green;
}
}
.loopingClass (@layout-width, @next-layout-width, @min-cols);
}
.loopingClass (@layout-width, @next-layout-width, @iteration) when (@layout-width <= @layout-max-width) {
@media (min-width:@layout-width) {
@{list} {
width: @layout-width;
}
@{item} {
&:nth-child(n) {
margin-right: @margin;
background: tomato;
}
&:nth-child(@{iteration}n) {
margin-right: 0;
background: green;
}
&:last-child {
background: green;
}
}
}
.loopingClass(@next-layout-width, @next-layout-width + @item-with-margin, @iteration + 1);
}
.box-layout(boxItemList,li,100px,120px,2,7,20px);
li
items are in oneul
. – AssuntaassuroffsetTop
ofnextElementSibling
, if it differs from theoffsetTop
of the target element, the target is the lastli
on a row. – Cascio