Skip to content Skip to sidebar Skip to footer

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() {
    var x = 0;
    var counter = 0;
    var boxesPerRow = 0;
    var elements = document.getElementsByClassName("item");
    var totalBoxes = elements.length;
        // Loop to find out how many boxes per row
        for (var i = 0; i < totalBoxes-2; i++){
            x = i+1;
            var temp = elements[i].getBoundingClientRect();
            if (x <= elements.length)
            {
                var next = elements[x].getBoundingClientRect();
                    // Compare height of current vs the next box
                    if (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 styling
        const boxes = boxesPerRow;
        var countUpTo = boxesPerRow;
        var counter = 0;

        // Loop through and apply color to boxes.
        for(var marker = 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)))
                {

                    var leftOver = marker-totalBoxes;

                    for(var c = 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"