【问题标题】:CSS Grid - Convert from flexbox layoutCSS Grid - 从 flexbox 布局转换
【发布时间】:2019-08-24 06:07:21
【问题描述】:

我正在尝试使用 CSS 网格实现以下布局...

我目前使用 flex 来生成这样的..

.row1 {
display:flex;
}

.row1 .item {
  background:red;
  width:50%;
  padding:20px;
  margin:10px;
  color:white;
  text-align:center;
}

.row2 {
display:flex;
}

.row2 .item {
  color:white;
  text-align:center;
  background:red;
  width:33%;
  padding:20px;
  margin:10px;
}
<div class="row1">
  <div class="item">
    Item
  </div>
  <div class="item">
    Item
  </div>
</div>

<div class="row2">
  <div class="item">
    Item
  </div>
  <div class="item">
    Item
  </div>
    <div class="item">
    Item
  </div>
</div>

这个但我正在尝试转换它,我怎样才能让它的 CSS 网格版本以这种模式重复动态内容?

【问题讨论】:

  • 使用 display:grid,你必须从 6 列模板开始,并为孩子们跨越 2 或 3 列

标签: html css flexbox css-grid


【解决方案1】:

使用display:grid,一个容器就足够了。要重复该模式,您可以使用nth-child(xn) 选择器。

例子

body {
  display: grid;
  grid-template-columns: repeat(6, 1fr);/* because it cannot be broken into 3 columns, but 2x3 columns*/
}

div {
  grid-column: auto/span 2;/* makes a third of the 6 cols */
}

div:nth-child(5n -3),
div:nth-child(5n - 4) {/* why 5n ? , because your pattern is made of 5 elements */
  grid-column: auto/span 3;/* to reset 2 of them to half width */
}


/* makeup */
div {
  padding: 1em;
  background: rgb(51, 103, 153);
  color: white;
  text-align: center;
  margin: 5px;
}

body {
  counter-reset: divs
}

div:before {
  counter-increment: divs;
  content: counter(divs)
}
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>

一些阅读可以更进一步并处理自己的下一个网格模板: 关于第n个孩子https://css-tricks.com/how-nth-child-works/

和网格:https://css-tricks.com/snippets/css/complete-guide-grid/ & https://gridbyexample.com/

【讨论】:

  • 谢谢,这很好用。也感谢您提供的 URL,现在阅读它们
【解决方案2】:

这个 CSS sn-p,是你可以开始的最简单的改变..

body > .container {
    display: grid;
    grid-templet-column: repeat(6,1fr);
    padding: 20px;
    grid-gap: 20px;
}

.container div {
    background: red;
    grid-column: span 2;
    padding: 20px;
    height: 1pc;
}

.container div:nth-child(5n+1),  .container div:nth-child(5n+1) + div {
    grid-column: span 3;
}

【讨论】:

    猜你喜欢
    • 2019-05-15
    • 1970-01-01
    • 2023-04-04
    • 2018-05-23
    • 1970-01-01
    • 2017-08-04
    • 2023-04-09
    • 2016-07-12
    相关资源
    最近更新 更多