3

我有以下无法更改的标记。我只能将<div>s 添加到包装容器中。

<div class="container">
   <div class="box" id="box1">1</div>
   <div class="box" id="box2">2</div>
   <div class="box" id="box3">3</div>
   <div class="box" id="box4">4</div>
   <div class="box" id="box5">5</div>
   <div class="box" id="box6">6</div>
</div>

可以<div>像下图那样堆叠 s 吗?

+------+--------+--------+
|   1  |    3   |    5   |
+------+--------+--------+
|      |        |        |
|   2  |    4   |    6   |
|      |        |        |
+------+--------+--------+
4

3 回答 3

3

个人定位

如果您只需要为这六列创建此布局,则可以单独放置它们,因为您有id's ,您可以<div>使用#id 选择器定位 all 。

不可扩展的解决方案 [演示]

此解决方案适用于您的六列布局,但如果您想扩展它并添加更多列,则需要在 CSS 中添加额外代码,例如.box:nth-child(8) {left: 150px;}.

.container {
   position: relative;
}
.box {
   width: 50px;
   height: 50px;
   float: left;
}
.box:nth-child(2n) {
   position: absolute;
   top: 50px;
}
.box:nth-child(2) {left: 0px;}
.box:nth-child(4) {left: 50px;}
.box:nth-child(6) {left: 100px;}

提高灵活性 [演示]

正如Itay所提到的,如果您使用该属性,则可以改进此解决方案transform,因此您可以使用以下方法修改 CSS:

.box:nth-child(4) {transform: translate(100%);}
.box:nth-child(6) {transform: translate(200%);}

您仍然需要top手动更改属性。也不要忘记使用供应商前缀,-webkit-或者-ms-如果你需要它们。

可扩展的解决方案 [演示]

此解决方案也使用 CSS3nth-child(n)选择器,但这里我们使用相对定位和margin-left属性技巧。box这个解决方案的源代码非常紧凑/可读,并且它是可扩展的,所以如果你添加更多的 es 到你的 es 中,你不必添加更多的 CSS 选择器container,只需简单地在你的 HTML 中添加一个新行,它就可以作为一个魅力.

.box {
   width: 50px;
   height: 50px;
   float: left;
   position: relative;
}
.box:nth-child(2n) {
   top: 50px;
   margin-left: -50px;
}

提高灵活性 [演示]

不要忘记您也可以使用以下transform属性改进此解决方案:

.box:nth-child(2n) {
   transform: translate(0, 100%);
   margin-left: -50px;
}

但是,您仍然需要margin-left手动设置属性。如果您没有找到通过 CSS 更改它的动态方法,您可以使用 JavaScript/jQuery。

CSS3 列

CSS3 将此作为一项新功能,因此您可以轻松创建自定义列。查看这篇文章了解更多,也看看Itay 的回答

于 2013-09-28T18:55:34.993 回答
2

备选方案 #1 - CSS 列

最简单的解决方案是使用CSS3 列

jsFiddle 演示

.container { 
   -webkit-columns: 3;
      -moz-columns: 3;
           columns: 3;
}

备选方案 #2 - CSS 转换

使用CSS 转换仍然非常灵活,但支持的浏览器比 CSS 列多。

jsFiddle 演示

.box:nth-child(n+2) {
    position: absolute;
    left: 0;
}
.box:nth-child(2n) {
    top: 100%;
}
.box:nth-child(3), .box:nth-child(4) {
    -webkit-transform: translateX(100%);
        -ms-transform: translateX(100%);
            transform: translateX(100%);
}
.box:nth-child(5), .box:nth-child(6) {
    -webkit-transform: translateX(200%);
        -ms-transform: translateX(200%);
            transform: translateX(200%);
}
于 2013-09-28T18:55:23.027 回答
0

如果我理解正确,请尝试将 box1 和 box2 包装到一个 div,然后对 box3 和 box4 执行相同操作,对 box5 和 box6 a 执行相同操作,然后将 float left 设置为那些包装 div,例如:

<div class="container">
  <div style="float:left">
    <div class="box" id="box1">1</div>
    <div class="box" id="box2">2</div>
  <div>
  <div style="float:left">
    <div class="box" id="box3">3</div>
    <div class="box" id="box4">4</div>
  </div>
  <div style="float:left">
    <div class="box" id="box5">5</div>
    <div class="box" id="box6">6</div>
  </div>
</div>
于 2013-09-28T18:50:59.927 回答