gpt4 book ai didi

html - 如何获得列数可变的网格布局的网格模板列的效果?

转载 作者:行者123 更新时间:2023-12-04 15:34:48 26 4
gpt4 key购买 nike

我有一个包含可变数量子项的 div。此代码已生成,我无法修改它。因此,仅使用 CSS,我需要在包含两行的表格中显示 div:

  • 第一行仅包含第一个 div(100% 宽度)
  • 另一个 div 共享第二行:每个 div 将具有相同的宽度,并且应该完全填满该行。

我尝试使用网格布局 + 网格模板列,但使用网格模板列并没有因为它假定我知道列数。例如,以下代码片段仅在有 4 个 child 时有效

.parent {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
}

.child:nth-child(1) {
grid-column: 1/-1;
}
Test with 3 children
<div class="parent" style="background-color:yellow;" >
<div class="child" style="background-color:red;">1</div>
<div class="child" style="background-color:blue;">2</div>
<div class="child" style="background-color:green;">3</div>
</div>
Test with 4 children
<div class="parent" style="background-color:yellow;" >
<div class="child" style="background-color:red;">1</div>
<div class="child" style="background-color:blue;">2</div>
<div class="child" style="background-color:green;">3</div>
<div class="child" style="background-color:orange;">4</div>
</div>
Test with 5 children
<div class="parent" style="background-color:yellow;" >
<div class="child" style="background-color:red;">1</div>
<div class="child" style="background-color:blue;">2</div>
<div class="child" style="background-color:green;">3</div>
<div class="child" style="background-color:orange;">4</div>
<div class="child" style="background-color:purple;">5</div>
</div>

最佳答案

Flexbox 可以做你想做的事

.parent {
display: flex;
flex-wrap: wrap;
margin-top: 1em;
}

.child {
flex: 1;
padding: .25em 0;
color:white;
font-size:1.25em;
}

.child:nth-child(1) {
flex: 1 0 100%;
}
Test with 3 children
<div class="parent" style="background-color:yellow;">
<div class="child" style="background-color:red;">1</div>
<div class="child" style="background-color:blue;">2</div>
<div class="child" style="background-color:green;">3</div>
</div>
Test with 4 children
<div class="parent" style="background-color:yellow;">
<div class="child" style="background-color:red;">1</div>
<div class="child" style="background-color:blue;">2</div>
<div class="child" style="background-color:green;">3</div>
<div class="child" style="background-color:orange;">4</div>
</div>
Test with 5 children
<div class="parent" style="background-color:yellow;">
<div class="child" style="background-color:red;">1</div>
<div class="child" style="background-color:blue;">2</div>
<div class="child" style="background-color:green;">3</div>
<div class="child" style="background-color:orange;">4</div>
<div class="child" style="background-color:purple;">5</div>
</div>

关于html - 如何获得列数可变的网格布局的网格模板列的效果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60100239/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com