htmlcsstiling

Fill in the free space in the last block


I'm trying to do a simple tiling in html/css.

When you click on a square, it disappears and the square next to it fills the remaining space. The problem is that the last square that remains is on the left (or right), and only takes up the middle of the screen. Can you please tell me how to make the last remaining square fill the whole screen? (The colors were used for clarity of work).

Here's the code:

var el = document.getElementsByClassName("square");
for (var i = 0; i < el.length; i++) {
  el[i].addEventListener("click", function() {
    this.remove();
  }, true);
}
html,
body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  display: flex;
}

.container {
  height: 100%;
  width: 100%;
  display: flex;
  flex-flow: column wrap;
}

.square {
  flex: 1 1 auto;
  background-color: gray;
  border: solid;
  margin: 1em;
}
<div class="container">
  <div style="background: darkred" class="square"></div>
  <div style="background: darkblue" class="square"></div>
</div>
<div class="container">
  <div style="background: darkgreen" class="square"></div>
  <div style="background: purple" class="square"></div>
</div>


Solution

  • You're removing the colored boxes, but they are contained in a <div class="container"> which are still present after you've clicked away the blocks.

    If you're removing the last box, you must also remove its container. Then the remaining boxes will also fill horizontal space.

    var el = document.getElementsByClassName("square");
    for (var i = 0; i < el.length; i++) {
      el[i].addEventListener("click", function() {
        if (this.parentElement.childElementCount === 1) {
            this.parentElement.remove();
        } else {
            this.remove();
        }
      }, true);
    }
    html,
    body {
      width: 100%;
      height: 100%;
      margin: 0;
      padding: 0;
      display: flex;
    }
    
    .container {
      height: 100%;
      width: 100%;
      display: flex;
      flex-flow: column wrap;
    }
    
    .square {
      flex: 1 1 auto;
      background-color: gray;
      border: solid;
      margin: 1em;
    }
    <div class="container">
      <div style="background: darkred" class="square"></div>
      <div style="background: darkblue" class="square"></div>
    </div>
    <div class="container">
      <div style="background: darkgreen" class="square"></div>
      <div style="background: purple" class="square"></div>
    </div>