提问人:Michael C. 提问时间:11/1/2023 最后编辑:JohannesMichael C. 更新时间:11/1/2023 访问量:55
如何反转每行的弯曲方向?
How can I reverse flex direction for each row?
问:
我正在尝试看看 flexbox 是否可行。我正在尝试完成 2 件事:
- div 容器宽度为 60%,另外 40%(因此每行只有 2 个项目,使 100%)
- 每行将反转(因此第一行为 60%/40%,然后下一行为 40%/60%)
我的设置如下(项目将始终相等,因此在本例中为 6 个项目,共 3 行)
.ImageContainer {
display: flex;
flex-wrap: wrap;
}
.ImageItem {
border:1px solid #000000;
}
.ImageItem:nth-child(even) {
width: 60%;
}
.ImageItem:nth-child(odd) {
width: 40%;
}
<div class="ImageContainer">
<div class="ImageItem">1</div>
<div class="ImageItem">2</div>
<div class="ImageItem">3</div>
<div class="ImageItem">4</div>
<div class="ImageItem">5</div>
<div class="ImageItem">6</div>
</div>
答:
-3赞
Lucian Claudiu
11/1/2023
#1
尝试像这样重构代码
.ImageContainer {
display: flex;
flex-wrap: wrap;
}
.ImageRow {
display: flex;
flex: 1;
width: 100%;
}
.ImageItem {
flex: 1;
}
.ImageItem:nth-child(even) {
flex: 60%;
}
.ImageItem:nth-child(odd) {
flex: 40%;
}
<div class="ImageContainer">
<div class="ImageRow">
<div class="ImageItem"></div>
<div class="ImageItem"></div>
</div>
<div class="ImageRow">
<div class="ImageItem"></div>
<div class="ImageItem"></div>
</div>
<div class="ImageRow">
<div class="ImageItem"></div>
<div class="ImageItem"></div>
</div>
</div>
CSS 没有父选择器或任何针对前兄弟姐妹的方法,这就是为什么您需要稍微调整一下 HTML 代码,如果它在某些方面有帮助,请告诉我
2赞
Johannes
11/1/2023
#2
对 flex 子项使用如下选择器。“:nth-child(4n+x)”将以 4 步为一组选择具有相应“x”偏移量的子项:
html,
body {
margin: 0;
}
.ImageContainer {
display: flex;
flex-wrap: wrap;
width: 100%;
}
.ImageItem {
border: 1px solid #ccc;
height: 60px;
box-sizing: border-box;
}
.ImageItem:nth-child(4n+1),
.ImageItem:nth-child(4n+4) {
width: 60%;
}
.ImageItem:nth-child(4n+2),
.ImageItem:nth-child(4n+3) {
width: 40%;
}
<div class="ImageContainer">
<div class="ImageItem"></div>
<div class="ImageItem"></div>
<div class="ImageItem"></div>
<div class="ImageItem"></div>
<div class="ImageItem"></div>
<div class="ImageItem"></div>
<div class="ImageItem"></div>
<div class="ImageItem"></div>
<div class="ImageItem"></div>
<div class="ImageItem"></div>
</div>
评论