Fill in the free space in the last block

76 Views Asked by At

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>

2

There are 2 best solutions below

2
Alec On BEST ANSWER

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>

0
Kiril On

There are still two <div class="container"> left, and the container still takes place, although rectangle disappear.

You need to check whether there is only one children left, if so – remove the container. Consider changing your js code to this:

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);
}