Reputation: 105015
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?
Upvotes: 5
Views: 2241
Reputation: 41
const calculateNumberOfRowsOfFlexBox = (children: any): number => {
if (!children) {
return -1
}
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 numberOfRows = calculateNumberOfRowsOfFlexBox(containerRef?.current?.children)
Upvotes: 4
Reputation: 371163
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.
Upvotes: 2