html - CSS Grid - 从 flexbox 布局转换

标签 html css flexbox css-grid

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

enter image description here

我目前使用 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,一个容器就足够了。要重复该模式,您可以使用 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个 child https://css-tricks.com/how-nth-child-works/

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

关于html - CSS Grid - 从 flexbox 布局转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55482830/

相关文章:

css - 如何使 flex block 在中心页面居中?

css - 如何将 flex-direction 和 flex-wrap 添加到同一行?

html - 如何使省略号在具有动态宽度的 flex 元素上工作( flex :1)?

javascript - 单击按钮时隐藏 div

javascript - 如何发送 HttpResponse(包括 JSON 和 html)

jquery - MVC3 Action 链接 - 触发 Jquery 的图像按钮

html - 图库在移动 View 中消失

css - CSS "not working"中的简单 div 当其中有文本时?

html - 同一行有两个 p 标签

html - 使用br标签如何显示和调整元素?