使用物品和物品填充固定宽度的网格一致的间距

时间:2014-12-09 22:50:45

标签: javascript html css

我希望用最小的css / js来实现这个目标:

http://i847.photobucket.com/albums/ab39/twilson90/Symbol2_zps04edc281.png

我有一个空间,需要填充相同尺寸的正方形。 在这个特定的例子中,我有一个270px宽度的空间,需要包含多个60px宽度框

我不能使用margin-right / bottom,这些框必须符合完美

我该怎么做?

1 个答案:

答案 0 :(得分:1)

这是我的270px宽盒子的解决方案,它装满了60px宽的盒子。底部的一行框展开以填充行并且完美。调整边距和宽度以适合您的情况。

请注意,我的HTML包含4个表,以提供可视化示例。你显然只会使用一张桌子。

.table {
  display: table;
  width: 270px;
  background-color: lightblue;
}
.tr {
  display: table-row;
}
.td {
  float: left;
  background-color: cadetblue;
  width: 60px;
  height: 60px;
  margin-right: 10px;
  margin-bottom: 10px;
}

/* Remove margin on right edge and bottom edge */
.tr .td:last-of-type {
  margin-right: 0;
}
.tr:last-of-type .td {
  margin-bottom: 0;
}

/* This makes the last row of boxes fill the row */
.tr:last-of-type .td:nth-child(1):nth-last-child(1) {
  width: 270px;
}
.tr:last-of-type .td:nth-child(1):nth-last-child(2),
.tr:last-of-type .td:nth-child(2):nth-last-child(1) {
  width: 130px;
}
.tr:last-of-type .td:nth-child(1):nth-last-child(3),
.tr:last-of-type .td:nth-child(2):nth-last-child(2),
.tr:last-of-type .td:nth-child(3):nth-last-child(1) {
  width: 83.333333px;
}
<div class="table">
  <div class="tr">
    <div class="td">1</div>
    <div class="td">2</div>
    <div class="td">3</div>
    <div class="td">4</div>
  </div>
  <div class="tr">
    <div class="td">5</div>
    <div class="td">6</div>
    <div class="td">7</div>
    <div class="td">8</div>
  </div>
  <div class="tr">
    <div class="td">9</div>
  </div>
</div>
<br>
<br>
<div class="table">
  <div class="tr">
    <div class="td">1</div>
    <div class="td">2</div>
    <div class="td">3</div>
    <div class="td">4</div>
  </div>
  <div class="tr">
    <div class="td">5</div>
    <div class="td">6</div>
    <div class="td">7</div>
    <div class="td">8</div>
  </div>
  <div class="tr">
    <div class="td">9</div>
    <div class="td">10</div>
  </div>
</div>
<br>
<br>
<div class="table">
  <div class="tr">
    <div class="td">1</div>
    <div class="td">2</div>
    <div class="td">3</div>
    <div class="td">4</div>
  </div>
  <div class="tr">
    <div class="td">5</div>
    <div class="td">6</div>
    <div class="td">7</div>
    <div class="td">8</div>
  </div>
  <div class="tr">
    <div class="td">9</div>
    <div class="td">10</div>
    <div class="td">11</div>
  </div>
</div>
<br>
<br>
<div class="table">
  <div class="tr">
    <div class="td">1</div>
    <div class="td">2</div>
    <div class="td">3</div>
    <div class="td">4</div>
  </div>
  <div class="tr">
    <div class="td">5</div>
    <div class="td">6</div>
    <div class="td">7</div>
    <div class="td">8</div>
  </div>
  <div class="tr">
    <div class="td">9</div>
    <div class="td">10</div>
    <div class="td">11</div>
    <div class="td">12</div>
  </div>
</div>