我正在尝试使用 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
,一个容器就足够了。要重复该模式,您可以使用 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/