gpt4 book ai didi

html - css-grid 2x2 或 2x3 布局,取决于元素的数量

转载 作者:太空宇宙 更新时间:2023-11-04 15:52:40 25 4
gpt4 key购买 nike

考虑一个元素数量可变的时间表,元素数量在 1 到 6 之间。如果有 1 - 4 个元素,它们应该覆盖 2x2 布局,例如:

ONE   TWO
THREE FOUR

如果有 5 - 6 个元素,它们应该覆盖 2x3 布局,例如:

ONE  TWO  THREE
FOUR FIVE SIX

Codepen Link

但是,我需要以编程方式将 x22x23 类应用于元素,具体取决于元素的数量。我更喜欢不需要在我的模板中添加额外逻辑的解决方案。

.grid {
border: 1px solid gray;
width: 400px;
height: 200px;
grid-gap: 5px;
display: grid;
grid-template-columns: repeat(6, 1fr);
grid-template-rows: repeat(2, 50%);
overflow: hidden;
}

.grid .x22,
.grid .x23 {
background-color: #1c1c1c;
color: white;
font-weight: bold;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}

.grid .x22 {
grid-column: span 3;
}

.grid .x23 {
grid-column: span 2;
}
<h2>2x3</h2>
<div class="grid">
<div class="x23">first</div>
<div class="x23">second</div>
<div class="x23">third</div>
<div class="x23">fourth</div>
<div class="x23">fifth</div>
<div class="x23">sixth</div>
</div>
<h2>2x2</h2>
<div class="grid">
<div class="x22">first</div>
<div class="x22">second</div>
<div class="x22">third</div>
<div class="x22">fourth</div>
</div>

最佳答案

如果不使用 Javascript,您可以使用 Flexbox 和一些 quantity queries 在纯 CSS 中实现此行为了解您有多少个 child 。

Codepen demo


标记

<section>
<div>1</div>
...
<div>6</div>
</section>

<section>
<div>1</div>
...
<div>5</div>
</section>


<section>
<div>1</div>
...
<div>4</div>
</section>

CSS

section {
margin-bottom: 4rem;
display: flex;
flex-wrap: wrap;
justify-content: space-between; }


/* by default assign flex-basis to 49.75% (2 boxes per row)
* the gap between box is .5%
*/

div {
display: flex;
justify-content: center;
align-items: center;
flex-grow: 0;
flex-shrink: 0;
flex-basis: 49.75%;
margin-bottom: .5%; }

/* if parent element contains at maximum 5 or 6 children we set their
* flex-basis to 33% (3 boxes per row, gap is still .5%)
*/

div:nth-last-child(n+5):first-child,
div:nth-last-child(n+5):first-child ~ *,
div:nth-last-child(n+6):first-child,
div:nth-last-child(n+6):first-child ~ * {
flex-basis: 33%; }


/* since we're setting space-around to `justify-content` we need to
* remove the extra space on the last row when we have exactly 5
* children, by adjusting the margin on the last child
*/
div:nth-child(5):last-child {
margin-right: auto;
margin-left: .5%; }

最终结果

enter image description here

关于html - css-grid 2x2 或 2x3 布局,取决于元素的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48638345/

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