I have the following HTML with CSS grid
Main
#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 that.main-item
has a fixedpositionin the grid.
I now add 25cellsto 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.main-item
(treat it as not existing). However, CSS now corrects this and makes the elements flow around.main-item
. I want the following secondary behavior:
I was able to correct this by settingstyle.gridRow
andstyle.gridColumn
in 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 all the other elements in JS? Is there CSS to prevent fixed elements from affecting flow correction?
Code Pen Link
You can give the grid a relative position and absolutely position specific grid items.