如何创建具有动态更改列宽的网格布局?

How can I create a grid layout with dynamically changing column widths?

我想为具有相同行高但不同列宽的图库创建动态变化的网格布局。我希望模式不断重复,无论添加的项目数量如何(图像将来自 JS 数组,HTML 将从带有变量的模板文字生成)。

这是JS:

let imgArray = ["img/img-1.jpg", "img/img-2.jpg", "img/img-3.jpg", "img/img-4.jpg", "img/img-5.jpg", "img/img-6.jpg", "img/img-7.jpg"
];

let galleryContainer = document.querySelector(".gallery-container");
 
galleryContainer.innerHTML += `${imgArray.map(img => `
<img src="${img}" alt="gallery-img" />`).join("")}
`;

所以我想要每行有两个不同宽度的网格列,像这样:

40% 60%

60% 40%

40% 60%

等等

我怎样才能做到这一点?它必须是带有 grid-auto-columns、nth-child 和 grid-column 的东西。预先感谢您的帮助。

这是一个工作示例:https://codepen.io/xgme/pen/wvegQVW

UI

<ul class="mytable">
   <li><div></div><div></div></li>
   <li><div></div><div></div></li>
   <li><div></div><div></div></li>
   <li><div></div><div></div></li>
   <li><div></div><div></div></li>
</ul>

CSS:

.mytable {
  width: 500px;
}
.mytable li {
  height: 20px;
  list-style:none;
  width: 100%;
}
.mytable li div {
  height:100%;
  float: left;
}
.mytable li:nth-child(even) div:nth-child(even) {
  width: 60%;
  background: blue;
}
.mytable li:nth-child(even) div:nth-child(odd) {
  width: 40%;
  background: green;
}
.mytable li:nth-child(odd) div:nth-child(even) {
  width: 40%;
  background: yellow;
}
.mytable li:nth-child(odd) div:nth-child(odd) {
  width: 60%;
  background: red;
}

使用 grid,您将需要一个包含 3 列的模板,40% 20% 40% 和 children 跨越 1 或两列成为 40%60% width.

你有一个重复的模式,:nth-child(n) 是用来设置 grid-column 跨越每个 N children。您的模式每 4 个元素重复一次,因此 :nth-child(4n) 是一个开始。

例子

section {
  display: grid;
  grid-template-columns: 40% 20% 40%;
  /* option */ /* gap : 5px ; */
}

section> :nth-child(4n - 2),
section> :nth-child(4n - 1 ) {/* sets for 2,3 6,7, 10,11 ... */
  grid-column: auto / span 2;
}


/* demo purpose */

section {
  counter-reset: divs;
}

div:before {
  counter-increment: divs;
  content:'N° ' counter(divs)
}
div:after {content:' 40%';margin:auto;font-weight:bold;font-size:1.5em;;}
section> :nth-child(4n - 2):after,
section> :nth-child(4n - 1):after {
content:' 60%';
}
div {
  border: solid 1px;
  padding: 1em;
  display:flex;
}
<section>
  <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>
</section>

我已经在此处分享了重复或相似的答案