【问题标题】:best way to arrange layout blocks排列布局块的最佳方式
【发布时间】:2015-09-16 13:52:47
【问题描述】:

我有 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}

【问题讨论】:

    标签: html css layout flexbox


    【解决方案1】:

    解决方案的关键成分是一个简单的float: left和使用css的calc()函数(幸好有quite good support these days)来占将这些像素与百分比混合:

    (我还添加了 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>

    【讨论】:

    • 请注意,4/3 计算和舍入会导致它在 Firefox 中无法正常工作。
    • 你可能是对的。我会把它留给例如66.66%33.33% 如果是这样的话。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-27
    • 2010-12-31
    • 1970-01-01
    • 1970-01-01
    • 2017-12-26
    • 2018-01-22
    • 1970-01-01
    相关资源
    最近更新 更多