Zebra Striping Rows In A Flex Container With Flex-wrap:wrap
Let's say I'm using a flexbox container with flex-direction:row and flex-wrap:wrap. Depending on the size of the browser window, I might have 2, 3, 4 or more items in each row. I w
Solution 1:
Okay, this is actually a fairly difficult task with flexboxes. The best way I could come up with is to use javascript to find out where the wrapping is happening by looping through and comparing the heights of the items. Currently, it is in a self-executing function and will only run on window load. If you want it to be responsive when someone changes a browser size after load then put it inside of a function and call that function on window resize.
Otherwise here is everything.
(function() {
varx=0;
varcounter=0;
varboxesPerRow=0;
varelements= document.getElementsByClassName("item");
vartotalBoxes= elements.length;
// Loop to find out how many boxes per rowfor (vari=0; i < totalBoxes-2; i++){
x = i+1;
vartemp= elements[i].getBoundingClientRect();
if (x <= elements.length)
{
varnext= elements[x].getBoundingClientRect();
// Compare height of current vs the next boxif (next.top > temp.top && counter ==0)
{
boxesPerRow = x;
counter = 1;
}
}
}
// var marker is where we are applying style// var countUpTo is the last box in the row we are stylingconstboxes= boxesPerRow;
varcountUpTo= boxesPerRow;
varcounter=0;
// Loop through and apply color to boxes.for(varmarker=0; marker < totalBoxes; marker++)
{
if(marker < countUpTo)
{
elements[marker].style.backgroundColor = "red";
}
else
{
counter++;
if(counter === 1)
{
countUpTo = boxes*(counter+2);
}
else{
countUpTo = countUpTo + (boxes*2);
}
marker = marker+boxes-1;
// Handles buttom row not being a full set of boxes.if(marker> totalBoxes && !(marker > totalBoxes-(boxes*2)))
{
varleftOver= marker-totalBoxes;
for(varc=1; c <= leftOver; c++)
{
elements[(totalBoxes-c)].style.backgroundColor = "red";
}
}
}
}
})();
Post a Comment for "Zebra Striping Rows In A Flex Container With Flex-wrap:wrap"