我的代码如下所示。它有效,但是非常重复。有谁知道如何使这种清洁剂?我认为我们应该使用重复或第n个孩子?
我对html和css有点陌生,请为我输入不好的代码感到抱歉。谢谢!
.grid-container {
display: grid;
grid-template-columns: repeat(8, auto);
grid-gap: 10px;
padding: 10px;
}
.item1 {
grid-row-start: 1;
grid-row-end: 1;
grid-column-start: 2;
grid-column-end: 8;
}
.item2 {
grid-row-start: 2;
grid-row-end: 2;
grid-column-start: 2;
grid-column-end: 4;
}
.item3 {
grid-row-start: 2;
grid-row-end: 2;
grid-column-start: 4;
grid-column-end: 6;
}
.item4 {
grid-row-start: 2;
grid-row-end: 2;
grid-column-start: 6;
grid-column-end: 8;
}
.item5 {
grid-row-start: 3;
grid-row-end: 3;
grid-column-start: 2;
grid-column-end: 4;
}
.item6 {
grid-row-start: 3;
grid-row-end: 3;
grid-column-start: 4;
grid-column-end: 6;
}
.item7 {
grid-row-start: 3;
grid-row-end: 3;
grid-column-start: 6;
grid-column-end: 8;
}
等...
ID与类之间的区别在于,ID可用于标识一个元素,而类可用于标识多个元素。在CSS中,类选择器是一个以句号(“。”)开头的名称,而ID选择器是以一个井号(“#”)开头的名称。
https://developer.mozilla.org/en-US/docs/Web/CSS/repeat
虽然您可以使用nth-child来管理,但是使用类是一种更简洁的方法。
由于您的元素跨越了1 / 3、1 / 2和所有列,因此您至少需要一个[[twelve列网格。
您无法将8列网格拆分为三分之二。
因此,只需应用类来指定每个div应该跨越多少列,如下所示:.container {
display: grid;
grid-template-columns: repeat(12, 1fr);
text-align: center;
gap: .25em;
margin: 1em;
}
.item {
border: 1px solid grey;
}
.span-12 {
grid-column: span 12;
}
.span-6 {
grid-column: span 6;
}
.span-4 {
grid-column: span 4;
}
<div class="container">
<div class="item span-12">Item 1</div>
<div class="item span-4">Item 2</div>
<div class="item span-4">Item 3</div>
<div class="item span-4">Item 4</div>
<div class="item span-4">Item 5</div>
<div class="item span-4">Item 6</div>
<div class="item span-4">Item 7</div>
<div class="item span-6">Item 8</div>
<div class="item span-6">Item 9</div>
<div class="item span-12">Item 10</div>
</div>
.grid-container {
display: grid;
grid-gap: 10px;
}
.grid-container>div {
grid-column: span 2;
border: 1px solid;
height: 20px;
}
.grid-container>div:nth-child(9n + 1) {
grid-column: span 6;
}
.grid-container>div:nth-child(9n - 1),
.grid-container>div:nth-child(9n) {
grid-column: span 3;
}
<div class="grid-container">
<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>