I have the following HTML with a CSS grid
<div id="grid">
<div class="main-item">Main</div>
</div>
#grid {
display: grid;
grid-template-columns: repeat(5, auto);
text-align: center;
}
#grid > * {
border: 1px solid blue;
padding: 20px;
}
#grid > .main-item {
grid-row: 3;
grid-column: 3 / 5;
background: rgba(0, 0, 0, 0.2);
}
The important part is .main-item has a fixed position in the grid.
I now add 25 cells to the grid.
const grid = document.querySelector("#grid");
for (let i = 0; i < 25; i++) {
const item = document.createElement("div");
item.innerText = i.toString();
grid.append(item);
}
The problem is that I want these elements to ignore the position of the .main-item (treat it as if it wasn’t there). However the CSS currently corrects for this and flows the elements around .main-item. I want the secondary behaviour below:
I can correct by setting style.gridRow and style.gridColumn in the JavaScript
item.style.gridRow = (Math.floor(i / 5) + 1).toString();
item.style.gridColumn = ((i % 5) + 1).toString();
Is there a way to do this without setting every other element in JS? Is there a CSS to prevent fixed element affecting the flow correction?
>Solution :
You can give the grid a relative position and position that specific grid item absolutely.
const grid = document.querySelector("#grid");
for (let i = 0; i < 25; i++) {
const item = document.createElement("div");
item.innerText = i;
grid.append(item);
}
#grid {
display: grid;
grid-template-columns: repeat(5, auto);
text-align: center;
position: relative;
}
#grid > * {
border: 1px solid blue;
padding: 20px;
}
#grid > .main-item {
position: absolute;
left: 0;
right: 0;
grid-row: 3;
grid-column: 3 / 5;
background: rgba(0, 0, 0, 0.2);
}
<div id="grid">
<div class="main-item">Main</div>
</div>
