3

I want to color stripe each row inside a multi-row flexbox

.container{ 
    display:flex;
    flex-flow: row wrap;
}

Has anyone discovered a simple way to determine the row count of a flexbox?

I looked at this question that did not accomplish the striping, but instead "manually" marks the Html element in order to stripe: Zebra striping a flexbox table with wrapping items

I looked at this question which accomplishes the task by programmatically calculating the row-breaks in JavaScript. It counts the number of different getBoundingClientRect .top in the container: zebra striping rows in a flex container with flex-wrap:wrap

I don't mind the JS, but, unfortunately, this solution also requires watching for changes in both the page layout and the content of each wrapped item inside the container.

Does anyone have a solution that doesn't require "manually" monitoring the layout and content?

Community
  • 1
  • 1
markE
  • 102,905
  • 11
  • 164
  • 176

2 Answers2

2

Considering that CSS has no way of knowing when an element wraps, a scripted solution is probably your best bet, unless the number of items per row is consistent throughout the container. Then you may be able to match individual items with CSS nth-child pseudo-classes, which could result in color-coded rows.

Community
  • 1
  • 1
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
0
 const calculateNumberOfRowsOfFlexBox = (children: any): number => {
   const items: any[] = Array.from(children)
   let baseOffset = items[0].offsetTop
   let numberOfRows = 0

   items.forEach(item => {
      if (item.offsetTop > baseOffset) {
         baseOffset = item.offsetTop
         numberOfRows += 1
      }
   })
   return numberOfRows
}

const numberOfRowscalculateNumberOfRowsOfFlexBox (containerRef?.current?.children)
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 10 '22 at 11:42