Incremental counting answered here depends on the grid items being in order and cannot deal with the irregular order caused by grid-auto-flow: dense
and individual grid-row
/ grid-column
.
Even if human isn't interested in pixel coordinates, script can convert them into grid indexes!
//// returnedArray[elmIdx] = {row: rowIdx, column: colIdx}
function measureGridIndexes(elms) {
const coords = {row: [], column: []}; // The two will be very sparse arrays
for (const [elmIdx, elm] of elms.entries()) {
const x = elm.offsetLeft, y = elm.offsetTop;
coords.row[y] ??= []; // An array of element indexes at the same Y pixel coordinate
coords.row[y].push(elmIdx);
coords.column[x] ??= []; // X ditto
coords.column[x].push(elmIdx);
}
const gridIdxs = [];
/// .flat() densifies a sparse array
for (const [rowIdx, elmIdxs] of coords.row.flat(0).entries()) {
for (const elmIdx of elmIdxs) {
gridIdxs[elmIdx] = {row: rowIdx};
}
}
for (const [colIdx, elmIdxs] of coords.column.flat(0).entries()) {
for (const elmIdx of elmIdxs) {
gridIdxs[elmIdx].column = colIdx;
}
}
return gridIdxs;
}
Demo: https://codepen.io/phroneris/pen/RwXOJZZ
Note, however, that this code only considers integer item coordinates.
And of course, this does not address cases where the position is further customized with individual margin
, position
, etc.
I wish no website would do such styling, which would throw away the advantages of grid layout...