我正在学习 CSS 中的网格以尝试使用此代码拆分一行
.grid-sample {
display: grid;
grid-template-columns: 1fr 1fr 1fr 1fr;
row-gap: 4rem;
padding: 0 5rem;
}
根据我的理解,
grid-template-columns: 1fr ...
线有助于将行分成 4 个偶数列。
有没有什么办法可以改进这段代码,让它根据项目的数量自适应地分割?例如,如果有 3 个项目,则该行应平均分成 3 列,而不是将项目排序到 4 的前 3 个位置。
提前谢谢你!
这可以用CSS网格实现,使用
grid-auto-columns
并将grid-auto-flow
设置为columns
:
document.querySelector('button').addEventListener('click', (e) => {
let button = e.currentTarget,
parent = button.nextElementSibling,
newChild = document.createElement('span');
parent.append(newChild);
});
.grid-sample {
display: grid;
grid-auto-columns: 1fr;
grid-auto-flow: column;
gap: 4rem;
padding: 0 5rem;
/* purely to generate content, otherwise irrelevant */
counter-reset: childCounter;
margin-block: 1rem;
}
span {
background-color: hsl(250deg 90% 85% / 1);
text-align: center;
}
span::before {
content: counter(childCounter, decimal-leading-zero);
counter-increment: childCounter;
}
<div class="grid-sample">
<span></span>
</div>
<div class="grid-sample">
<span></span>
<span></span>
<span></span>
</div>
<div class="grid-sample">
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>
<div class="grid-sample">
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>
<button type="button">Add span</button>
<div class="grid-sample">
<span></span>
</div>
值得注意的是,这确实有一个不幸的问题,即继续将新元素放入新列(如
grid-auto-flow
指定),而不是在空间被最大填充时换行。
鉴于这种情况,使用 flex-box 布局可能会更好,例如:
document.querySelector('button').addEventListener('click', (e) => {
let button = e.currentTarget,
parents = document.querySelectorAll('section > div'),
newChild = document.createElement('span');
parents.forEach(
(el) => el.append(newChild.cloneNode())
)
});
section {
box-sizing: border-box;
inline-size: clamp(40rem, 90%, 1100px);
margin-inline: auto;
padding: 0;
}
.grid-sample,
.flex-sample {
gap: 2rem;
padding: 0 2rem;
/* purely to generate content, otherwise irrelevant */
counter-reset: childCounter;
margin-block: 1rem;
}
.grid-sample {
display: grid;
grid-auto-columns: 1fr;
grid-auto-flow: column;
}
.flex-sample {
display: flex;
flex-flow: row wrap;
justify-content: start;
}
span {
background-color: hsl(250deg 90% 85% / 1);
flex-grow: 1;
padding: 0.5rem;
text-align: center;
}
span::before {
content: counter(childCounter, decimal-leading-zero);
counter-increment: childCounter;
}
<button>Add new child</button>
<section>
<div class="grid-sample">
<span></span>
</div>
</section>
<section>
<div class="flex-sample">
<span></span>
</div>
</section>