I'm amateur with CSS grid layout. What I'm trying to do is removing some elements in the grid with an onclick() event, and making the remaining elements reposition and get in the shape of the removed ones like this:
My codes remove "A" from the grid, but unable to change the shape of "B" and "C". Is there a way to achieve this with css or very simple js? I will have many other buttons to remove many other cells, so I'm trying to keep the codes as short as possible.
HTML
<div class="container">
<div class="grid a">Grid A</div>
<div class="grid b">Grid B</div>
<div class="grid c">Grid C</div>
<div class="grid a">Grid A</div>
<div class="grid b">Grid B</div>
<div class="grid c">Grid C</div>
<div class="grid a">Grid A</div>
<div class="grid b">Grid B</div>
<div class="grid c">Grid C</div>
</div>
<div class="button" onclick="hide()">Hide Grid A</div>
JS
function hide() {
var element = document.getElementsByClassName("a");
var i;
for (i=0; i<element.length; i++) {
if (element[i].style.display) {
element[i].style.display = null;
}
else {element[i].style.display = "none";
}
}
}
CSS
.container {
width: 500px;
margin: auto;
display: grid;
grid-gap: 10px;
grid-template-columns: repeat(4, 1fr);
grid-auto-rows: 100px;
counter-reset: div;
}
.grid {
border: solid;
}
.grid:nth-child(6n + 1), .grid:nth-child(6n + 4) {
grid-column: auto /span 2;
grid-row: auto /span 2;
}
You've hidden the elements from the view, but that doesn't change the how the grid is processed and setup.
You need to actually remove the elements from the DOM.
Check out https://replit.com/@cmorrreplit/TestingGridChange for a working example.