安排布局块的最佳方式

best way to arrange layout blocks

我有一个包含 9 个 div 的容器,我想按以下方式排列元素:

看起来像这样:

 _________ ____ ____
| A       | B  | C  |
|         |____|____|
|         | D  | E  |
|_________|____|____|
| F  | G  | H  | I  |
|____|____|____|____|

其中所有元素始终为正方形(宽度 = 高度),我将确定它们在容器外的百分比大小。 例如,在上面的示例中,A 尺寸(宽度和高度)= 宽度的 50%,B 尺寸 = 25%。我还想在每个元素之间留出大约 5px 的边距。

我的尝试如下

    <div id="grid">
        <div class="block big">
        </div>
        <div class="block small">
        </div>
        <div class="block small">
        </div>
        <div class="block small">
        </div>
        <div class="block small">
        </div>
        <div class="block small">
        </div>
        <div class="block small">
        </div>
        <div class="block small">
        </div>
        <div class="block small">
        </div>
    </div>

和css:

#grid {width: 90%; position: relative}
.block {margin: 5px; background-size: cover; position: relative; display: inline-block}
.big {width: 50%; height: 0; padding-bottom: 50%; background-color: #eee}
.small {width: 25%; height: 0; padding-bottom: 25%; background-color: #eee}

解决方案的关键是简单的float: left和使用csscalc() 函数(幸运的是有 quite good support these days)来解释这些像素与百分比的混合:

(我还添加了 border-box 尺寸,这样我用来显示框的边框就不会弄乱 up/complicate 计算)

* {
  box-sizing: border-box;
}
#grid {
  width: 400px;
  height: 300px;
  border: solid 2px gray;
}
.block {
  min-width: 10px;
  min-height: 10px;
  border: solid 2px blue;
  float: left;
  margin: 5px;
}
.block.big {
  width: calc(50% - 10px);
  height: calc(50%*4/3 - 10px);
}
.block.small {
  width: calc(25% - 10px);
  height: calc(25%*4/3 - 10px);
}
<div class="grid">
  <div id="grid">
    <div class="block big">
    </div>
    <div class="block small">
    </div>
    <div class="block small">
    </div>
    <div class="block small">
    </div>
    <div class="block small">
    </div>
    <div class="block small">
    </div>
    <div class="block small">
    </div>
    <div class="block small">
    </div>
    <div class="block small">
    </div>
  </div>
</div>