问题
I am trying to understand how to achieve a layout that takes two columns in the first row and three columns in the second row, third row, and so on.
<section>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
</section>
//CSS
section {
display: grid;
grid-template-columns: 1fr 1fr;
}
The above code will give me two-column layout but how to modify it to achieve mentioned layout.
回答1:
You can try like below:
section {
display: grid;
grid-template-columns: repeat(6, 1fr);
grid-gap: 5px;
}
section div {
grid-column: span 3;
height: 50px;
background: red;
}
section div:nth-child(n + 3) {
grid-column: span 2;
}
<section>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
</section>
回答2:
This is what I wanted actually.
section {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-gap: 5px;
}
div {
height: 50px;
background: red;
}
div:first-child {
grid-column: 1 / 3;
}
<section>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
</section>
来源:https://stackoverflow.com/questions/61398763/css-grid-two-columns-in-the-first-row-and-three-columns-in-the-second-and-third