CSS Grid - Convert from flexbox layout

2020-03-31 04:35发布

I am trying to achieve the following layout using CSS grid...

enter image description here

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>

this but am trying to convert it, how could I make the CSS grid version of it repeat in this pattern for dynamic content?

2条回答
Juvenile、少年°
2楼-- · 2020-03-31 05:22

With display:grid, a single container is enough. to repeat the pattern, you can use the nth-child(xn) selector.

example

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>

Some reading to go farther and handle yourself your next grid templates : about nth-child https://css-tricks.com/how-nth-child-works/

and grid : https://css-tricks.com/snippets/css/complete-guide-grid/ & https://gridbyexample.com/

查看更多
一夜七次
3楼-- · 2020-03-31 05:25

This CSS snippet, is easiest change you can start with..

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;
}
查看更多
登录 后发表回答