【问题标题】:Css block layout - even/odd?CSS块布局 - 偶数/奇数?
【发布时间】:2018-07-12 07:51:17
【问题描述】:

我正在开发 Wordpress 网站的前端。项目布局为:每行2个项目。第一个项目是 2/3 宽度,第二个是 1/3 宽度,第三个也是 1/3,第四个是 2/3。可以有无限数量的项目,但最后一个项目总是 100% 宽度。

这可以通过仅使用 CSS 来完成吗? 我想到了 :nth-child(odd) 和 :nth-child(even)。但有时奇数是 2/3,有时是另一个……

感谢您的帮助。

【问题讨论】:

  • @TemaniAfif 我不会将此标记为重复,因为最后一个元素必须具有 100% 的宽度。
  • @dennis-perremans 如果最后一个项目总是 100% 宽度并且有偶数个瓦片,那么最后两个将是 100% 宽度?
  • @shirfy 我没有标记为重复;)我只是将其评论为可能的重复,以便他了解...您可能会注意到我有 Gold CSS,所以如果我确定它会立即关闭:)
  • @shirfy 如果瓷砖的数量是偶数,则不会有最后一个宽度为 100%。仅当图块数量为奇数时,最后一个应为 100%。

标签: css layout


【解决方案1】:

尝试使用以下结构来创建您想要的布局。

    .container div {
      width:100px;
      height:100px;
      display: inline-block;
      border:solid 1px blue;
      margin:5px;
    }
    .container section {
      width:100%;
      display:flex;
    }
    .container section:nth-child(odd) > div:nth-child(even) {
       width:75%;
    }
    .container section:nth-child(odd) > div:nth-child(odd) {
       width:24%;
    }
    .container section:nth-child(even) > div:nth-child(odd) {
      width:75%;
    }
    .container section:nth-child(even) > div:nth-child(even) {
        width:24%;
    }
    .container section:last-child > div:nth-child(1) { 
      border: solid 1px red !important;
      width:100%;
    }
<div class="container">
    <section> 
    <div> 1 </div>
    <div> 2 </div>
    </section>
    <section>
    <div> 3 </div> 
    <div> 4 </div> 
    </section>

    <section> <div> 5 </div> </section>
</div>

【讨论】:

  • @SuperDJ 不可能在每 2 个元素周围放置一个部分。
  • @DennisPerremans 这不是我的答案,我只编辑了答案。它们不必是部分。它们也可以是具有特定类的任何元素。所以并不总是会给你一个复制粘贴的答案。有些只会给你指向正确答案的指针
  • @DennisPerremans 我已经添加了另一个答案,看看它是否解决了你的问题。
【解决方案2】:

这里没有部分/外部元素:

.container {
  display: flex;
  flex-wrap: wrap;
}

.container div {
  width: 100px;
  height: 100px;
  display: inline-block;
  border: solid 1px blue;
  margin: 5px;
  width: 24%;
}

.container div:nth-child(2n),
.container div:nth-child(3n) {
  width: 73%;
}

.container div:nth-child(2n+3) {
  width: 73%;
}

.container div:nth-child(4n),
.container div:nth-child(4n+1) {
  width: 24%;
}

.container div:last-child {
  border: solid 1px red !important;
  width: 100%;
}
<div class="container">

  <div> 1 </div>
  <div> 2 </div>
  <div> 3 </div>
  <div> 4 </div>
  <div> 5 </div>
  <div> 6 </div>
  <div> 7 </div>
  <div> 8 </div>
  <div> 1 </div>
  <div> 2 </div>
  <div> 3 </div>
  <div> 4 </div>
  <div> 5 </div>
  <div> 6 </div>
  <div> 7 </div>
  <div> 8 </div>
  <div> Last </div>
</div>

【讨论】:

    猜你喜欢
    • 2014-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-16
    • 2017-02-06
    • 2016-04-21
    相关资源
    最近更新 更多