javascript - zebra striping rows in a flex container with flex-wrap:wrap -
let's i'm using flexbox container flex-direction:row
, flex-wrap:wrap
.
depending on size of browser window, might have 2, 3, 4 or more items in each row.
i want put grey background in items in every other row, mimicking table layout. there easy way this?
example fiddle here: https://jsfiddle.net/mqf7nouc/1/
html:
<div class="container"> <div class="item"> item 1 </div> <div class="item"> item 2 </div> <div class="item"> item 3 </div> <div class="item"> item 4 </div> <div class="item"> item 5 </div> <div class="item"> item 6 </div> <div class="item"> item 7 </div> </div>
css:
.container { display:flex; flex-direction:row; flex-wrap:wrap; } .item { height:50px; width:100px; text-align:center; vertical-align:middle; line-height:50px; border:1px solid black; margin:5px; }
okay, difficult task flexboxes. best way come use javascript find out wrapping happening looping through , comparing heights of items. currently, in self-executing function , run on window load. if want responsive when changes browser size after load put inside of function , call function on window resize.
otherwise here everything.
(function() { var x = 0; var counter = 0; var boxesperrow = 0; var elements = document.getelementsbyclassname("item"); var totalboxes = elements.length; // loop find out how many boxes per row (var = 0; < 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 next box if (next.top > temp.top && counter ==0) { boxesperrow = x; counter = 1; } } } // var marker applying style // var countupto last box in row styling const boxes = boxesperrow; var countupto = boxesperrow; var counter = 0; // loop through , apply color 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 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"; } } } } })();
Comments
Post a Comment