如何创建这种交替布局?

时间:2018-05-26 09:55:38

标签: html css css-selectors

这是我需要使用的HTML:

<div class="images">
  <div class="image"></div>
  <div class="image"></div>
  <div class="image"></div>
  ...
</div>

我试过了:nth-child() even/odd/xn+x等等 - 没有运气,我无法弄清楚要做什么计算。如果需要,可以通过PHP添加动态CSS类。

我试图实现这种布局:

enter image description here

3 个答案:

答案 0 :(得分:5)

你可以尝试这样的事情。您的模式重复每4个元素,因此您需要考虑nth-child(4n + x)

&#13;
&#13;
.images {
  display:flex;
  min-height:100vh;
  flex-wrap:wrap;
  align-content:flex-start;
}
.image {
  height:50px;
  border:1px solid;
  box-sizing:border-box;
}

.image:nth-child(4n+1),
.image:nth-child(4n+4) {
   width:40%;
   background:red;
}

.image:nth-child(4n+2),
.image:nth-child(4n+3) {
   width:60%;
   background:blue;
}
&#13;
<div class="images">
  <div class="image"></div>
  <div class="image"></div>
  <div class="image"></div>
  <div class="image"></div>
  <div class="image"></div>
  <div class="image"></div>
  <div class="image"></div>
  <div class="image"></div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:3)

事实上,您可以从接受的答案中简化CSS:

.images {
  display:flex;
  min-height:100vh;
  flex-wrap:wrap;
  align-content:flex-start;
}
.image {
  height:50px;
  border:1px solid;
  box-sizing:border-box;
  width:60%;
  background:blue;
}

.image:nth-child(4n),
.image:nth-child(4n+1) {
   width:40%;
   background:red;
}
<div class="images">
  <div class="image"></div>
  <div class="image"></div>
  <div class="image"></div>
  <div class="image"></div>
  <div class="image"></div>
  <div class="image"></div>
  <div class="image"></div>
  <div class="image"></div>
</div>

答案 2 :(得分:-1)

.images .odd {
    float:left;
}
.images .even {
    float:right;
}
<div class="images">
  <div class="image odd"></div>
  <div class="image even"></div>
  <div class="image odd"></div>
</div>