首页 > 解决方案 > 填充最后一个块的空闲空间

问题描述

我正在尝试在 html/css 中进行简单的平铺。

当您单击一个正方形时,它会消失,并且它旁边的正方形会填满剩余空间。问题是剩下的最后一个方块在左边(或右边),只占据屏幕的中间。你能告诉我如何让最后剩下的方块填满整个屏幕吗?(颜色用于工作的清晰度)。

这是代码:

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>

标签: htmlcsstiling

解决方案


您正在删除彩色框,但它们包含在<div class="container">您单击离开块后仍然存在的 a 中。

如果要移除最后一个框,则还必须移除其容器。然后剩下的盒子也将填充水平空间。

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>


推荐阅读