The goal is to set the style and get the bounding box of a whole "row" in a css grid.
(Style setting such as highlight when hovering).
For setting the style there is the specific feature to use display: contents
so the styles can affect the child elements without influencing the tree.
However I notice that if I then try to get the size (height) of that row the getBoundingClientRect
returns all zeros.
const row = document.getElementById("firstrow");
console.log(row.getBoundingClientRect());
const actual_cell = document.getElementById("data");
console.log(actual_cell.getBoundingClientRect());
.grid {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
}
.row {
display: contents;
}
.row:hover div {
background-color: lightgray;
}
.cell {
border: 1px black solid;
max-height: 100px;
}
.ipsum {
height: 200px;
max-height: 300px;
}
<div class="grid">
<div class="row" id="firstrow">
<div class="cell">hello</div>
<div class="cell" id="data">world</div>
<div class="cell ipsum">ipsum lorem</div>
</div>
</div>
Of course I could iterate everything "below" the row. However this is quite a complex way, as not only getting the max height of the element, one has to check how it is displayed (pop up menus, or nested display:contents
etc) and where (maybe the row is actually spanning multiple rows and there are 4 cells in above example in a "row").
So can this be done in an easy way?
3
Answers
You could set the style of the row with JavaScript to match that of your grid; get your values; and, then remove the inline styles to reset the row to
display: contents
.Yes, Elements with
display: contents
feel weird as if they are and are not in the DOM at the same time.Getting the bounds and covering the row with a red div:
It seems that you can get the height of one row in
px
through the computed value of thegrid-template-rows
property of the grid element.This computed value will return a list of all the rows’s computed height, you can then grab the one you’re interested in by splitting the resulting string and getting the value at the index you wish: