gpt4 book ai didi

css - 动态列表元素的选择器问题

转载 作者:行者123 更新时间:2023-11-28 19:19:48 25 4
gpt4 key购买 nike

请查看代码演示以便于理解。

当列表元素显示为两列时,可以使用如下方法实现页面响应式设计。

.test {
display:flex;
flex-wrap:wrap;
justify-content:space-between;
}
.test div {
width:calc(50% - 30px);
padding:10px 0 10px 10px;
margin:8px;
background:#ffc107;
}
.test div:nth-last-of-type(1):nth-child(odd) {
width:100%;
}
<div class="test">
<div>text</div>
<div>text</div>
<div>text</div>
<div>text</div>
<div>text</div>
<div>text</div>
<div>text</div>
</div>

当列表超过两列时,上述方法不再适用。

例如,下面的列表有四列。如何选取最后一行的奇数元素?

.test {
display:flex;
flex-wrap:wrap;
justify-content:space-between;
}
.test div {
width:calc(25% - 30px);
padding:10px 0 10px 10px;
margin:8px;
background:#ffc107;
}
<div class="test">
<div>text</div>
<div>text</div>
<div>text</div>
<div>text</div>
<div>text</div>
<div>text</div>
<div>text</div>
<div>text</div>
<div>text</div>
<div>text</div>
<div>text</div>
</div>

是否有针对此问题的 CSS 选择器解决方案?

最佳答案

您需要将 width: 声明替换为 flex: 声明:

flex: 1 0 calc(25% - 30px);

flex 是一个简写声明,声明:

  • flex 增长
  • flex 收缩
  • flex 基础

最后一个值 (flex-basis) 声明了元素的默认宽度,其他都相同。

如果最后一行的元素更多或更少,则 flex-growflex-shrink 指示这些元素相对于空间应该增长或收缩多少需要填写。

工作示例:

.test {
display: flex;
flex-wrap: wrap;
justify-content:space-between;
}
.test div {
flex: 1 0 calc(25% - 30px);
padding: 10px 0 10px 10px;
margin: 8px;
background: #ffc107;
}
<div class="test">
<div>text</div>
<div>text</div>
<div>text</div>
<div>text</div>
<div>text</div>
<div>text</div>
<div>text</div>
<div>text</div>
<div>text</div>
<div>text</div>
<div>text</div>
</div>

关于css - 动态列表元素的选择器问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57553891/

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