简体   繁体   中英

CSS: Reposition remaining grid elements after onclick event removes some

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? Js would be fine too, if css is not enough alone

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM