我正在尝试进行布局(下图),我希望HTML遵循相同的格式,因为这将拉动动态内容。
这里有2行,添加更多动态内容后,这些行将重复进行以遵循设计。
我尝试使用display:grid;并显示:flex;但目前无法正确创建它。
我已经在下面创建了此文件,但是它只适用于一行。我想知道是否有更好的解决方法,还是有人可以提供答案?
Codepen:-https://codepen.io/scottYg55/pen/VwwPqXB?&editable=true
.wrapper {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-auto-rows: 100px;
}
.wrapper>div {
background: blue;
border: 1px solid black;
}
.wrapper>div:nth-of-type(1) {
grid-column-start: 1;
grid-column-end: 2;
grid-row-start: 1;
grid-row-end: 3;
}
.wrapper>div:nth-of-type(4) {
grid-column-start: 3;
grid-row-start: 1;
grid-row-end: 3;
background: red;
}
<div class="wrapper">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
<div>10</div>
<div>11</div>
<div>12</div>
<div>13</div>
<div>14</div>
<div>15</div>
<div>16</div>
</div>
您的模式每9个元素重复一次,因此您可以在下面考虑nth-child(9n + x)
的地方尝试尝试类似的事情>>
.wrapper { display: grid; grid-template-columns: repeat(3, 1fr); grid-auto-flow:dense; /* to fill all the empty cells */ grid-auto-rows: 50px; } /* 2 rows for 1 and 4 and 7*/ .wrapper > div:nth-child(9n + 1), .wrapper > div:nth-child(9n + 4), .wrapper > div:nth-child(9n + 7) { grid-row:span 2; background:red; } /* force the 3rd element on column 2*/ .wrapper > div:nth-child(9n + 3) { grid-column:2; } /* force the 6th element on column 1*/ .wrapper > div:nth-child(9n + 6) { grid-column:1; } .wrapper>div { background: blue; border: 1px solid black; color:#fff; font-size:2em; }
<div class="wrapper"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> <div>6</div> <div>7</div> <div>8</div> <div>9</div> <div>10</div> <div>11</div> <div>12</div> <div>13</div> <div>14</div> <div>15</div> <div>16</div> <div>17</div> <div>18</div> </div>
您还可以考虑将模式重复每3个元素并优化代码,如下所示:
.wrapper { display: grid; grid-template-columns: repeat(3, 1fr); grid-auto-flow:dense; /* to fill all the empty cells */ grid-auto-rows: 50px; } .wrapper > div:nth-child(3n + 1) { grid-row:span 2; background:red; } /* force the 3rd element on column 2*/ .wrapper > div:nth-child(9n + 3) { grid-column:2; } /* force the 6th element on column 1*/ .wrapper > div:nth-child(9n + 6) { grid-column:1; } .wrapper>div { background: blue; border: 1px solid black; color:#fff; font-size:2em; }
<div class="wrapper"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> <div>6</div> <div>7</div> <div>8</div> <div>9</div> <div>10</div> <div>11</div> <div>12</div> <div>13</div> <div>14</div> <div>15</div> <div>16</div> <div>17</div> <div>18</div> </div>
您为什么不尝试使用网格模板区域?