Mix grid autolayout with fixed column and column positions
P粉492959599
P粉492959599 2023-09-15 16:01:55
0
1
451

I have the following HTML with 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 that .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 .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 setting style.gridRow and style.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

P粉492959599
P粉492959599

reply all(1)
P粉440453689

You can give the grid a relative position and absolutely position specific grid items.

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>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template