左右浮动元素,下方有明显的移除间距

时间:2016-02-02 03:12:33

标签: html css alignment css-float multiple-columns

所以我有以下代码:

body {
  counter-reset: section;
}

.evens-and-odds {
  div {
    display: inline-block;
    height: 80px;
    width: calc(50% - 10px);
    margin: 5px;
    padding: 10px 0;
    text-align: center;
    font-size: 30px;
    color: #FFF;
    &:nth-of-type(odd) {
      float: left;
      clear: left;
      background-color: deeppink;
      &:before {
        counter-increment: section;
        content: "Odd: " counter(section);
      }
    }
    &:nth-of-type(even) {
      float: right;
      background-color: lime;
      &:before {
        counter-increment: section;
        content: "Even: " counter(section);
      }
    }
    &:nth-of-type(3) {
     height: 200px 
    }
    &:nth-of-type(5) {
      height: 400px;
    }
    &:nth-of-type(6) {
      height: 300px;
    }
  }
}

以下完整演示:

http://codepen.io/crashy/pen/QyBvyG

您会注意到,在较大的元素下,对面(左侧或右侧)有空白区域。我基本上希望元素能够流动起来,我的想法是每个列都应该被隔离,但我不能使用包装div来实现这个浮动(或其他一些CSS魔法)。

更喜欢免费的JavaScript解决方案。

1 个答案:

答案 0 :(得分:0)

如果您想在CSS中执行此操作,那么它会变得复杂。我建议你用HTML做这个,只需将两个div中的evens和odds分开,你就会很好。

好的。您可以将所有赔率浮动到左侧,并从平均值中移除浮动。因此,即使左侧div(赔率)更大并且没有空白区域,右侧div(均衡)也会堆叠起来。

这是我的解决方案:

body {
  counter-reset: section;
}

.evens-and-odds {
  div {
    display: table;
    height: 80px;
    width: calc(50% - 10px);
    margin: 5px;
    padding: 10px 0;
    text-align: center;
    font-size: 30px;
    color: #FFF;
    &:nth-of-type(odd) {
      display: table-cell;
      float: left;
      clear: left;
      background-color: deeppink;
      &:before {
        counter-increment: section;
        content: "Odd: " counter(section);
      }
    }
    &:nth-of-type(even) {
      display: table-cell;
      float: right;
      clear: right;
      background-color: lime;
      &:before {
        counter-increment: section;
        content: "Even: " counter(section);
      }
    }
  }
}

英语不是我的第一语言,对不起,如果我只是漫无边际的话。