One way to get the number of rows/columns of a css grid is by using the grid-template-rows
or grid-template-columns
from the computed style of the grid window.getComputedStyle(grid)
.
The returned values are always transformed to separated pixel values (e.g. 20px 20px 50px), where each value represents the size of the respective column/row. All that’s left to do is splitting up the string into an array and counting the number of values.
const gridComputedStyle = window.getComputedStyle(grid);
// get number of grid rows
const gridRowCount = gridComputedStyle.getPropertyValue("grid-template-rows").split(" ").length;
// get number of grid columns
const gridColumnCount = gridComputedStyle.getPropertyValue("grid-template-columns").split(" ").length;
console.log(gridRowCount, gridColumnCount);
Here is the full snippet (Codepen):
function getGridData () {
// calc computed style
const gridComputedStyle = window.getComputedStyle(grid);
return {
// get number of grid rows
gridRowCount: gridComputedStyle.getPropertyValue("grid-template-rows").split(" ").length,
// get number of grid columns
gridColumnCount: gridComputedStyle.getPropertyValue("grid-template-columns").split(" ").length,
// get grid row sizes
gridRowSizes: gridComputedStyle.getPropertyValue("grid-template-rows").split(" ").map(parseFloat),
// get grid column sizes
gridColumnSizes: gridComputedStyle.getPropertyValue("grid-template-columns").split(" ").map(parseFloat)
}
}
window.addEventListener("DOMContentLoaded", outputGridData);
window.addEventListener("resize", outputGridData);
function outputGridData () {
const gridData = getGridData();
output.textContent = `
Rows: ${gridData.gridRowCount}
Columns: ${gridData.gridColumnCount}
Rows sizes: ${gridData.gridRowSizes}
Column sizes: ${gridData.gridColumnSizes}
`;
}
#grid {
display: grid;
grid-gap: 20px;
grid-template-columns: repeat(auto-fill, 200px);
}
#output {
white-space: pre-wrap;
}
.A, .B, .C {
font-family: Arial;
font-weight: 600;
font-size: 2rem;
border-radius: 50% 50%;
width: 80px;
height: 80px;
text-align: center;
line-height: 80px;
box-shadow: -3px 5px 20px -3px #AAA;
border: solid 10px #fff;
color: #fff;
}
.A {
background: #ffc300;
}
.B {
background: #c70039;
}
.C {
background: #581845;
}
<div id="output"></div>
<div id="grid">
<div class="A">A</div>
<div class="B">B</div>
<div class="C">C</div>
<div class="A">A</div>
<div class="B">B</div>
<div class="C">C</div>
<div class="A">A</div>
<div class="B">B</div>
<div class="C">C</div>
<div class="A">A</div>
<div class="B">B</div>
<div class="C">C</div>
</div>