CSS网格-从flexbox布局转换 [英] CSS Grid - Convert from flexbox layout
问题描述
我正在尝试使用CSS网格实现以下布局...
I am trying to achieve the following layout using CSS grid...
我目前使用flex来生成它..
I currently use flex to generate it like this..
.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网格版本在这种模式下重复显示动态内容?
this but am trying to convert it, how could I make the CSS grid version of it repeat in this pattern for dynamic content?
推荐答案
对于display:grid
,一个容器就足够了.要重复图案,可以使用nth-child(xn)
选择器.
With display:grid
, a single container is enough. to repeat the pattern, you can use the nth-child(xn)
selector.
示例
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>
一些阅读内容可以帮助您进一步处理下一个网格模板: 关于nth-child https://css-tricks.com/how-nth-child -works/
Some reading to go farther and handle yourself your next grid templates : about nth-child https://css-tricks.com/how-nth-child-works/
和网格: https://css-tricks.com/snippets/css/complete-guide-grid/& https://gridbyexample.com/
and grid : https://css-tricks.com/snippets/css/complete-guide-grid/ & https://gridbyexample.com/
这篇关于CSS网格-从flexbox布局转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!