排列布局块的最佳方式



我有一个有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()函数(幸运的是,现在它有很好的支持)来解释这些像素与百分比的混合:

(我还添加了border-box大小,这样我用来显示框的边框就不会弄乱/使计算复杂化)

* {
  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>

最新更新