Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mixing grid auto layout with a fixed row-column position

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:

enter image description here

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?

Codepen Link

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading