当 flex-item 换行到新行时,我可以将 CSS 应用到它吗?

ton*_*120 6 html javascript css flexbox

.wrapper {
  border: 5px solid pink;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.a-fc {
  background-color: purple;
  width: 300px;
  /*height: 100px;*/
}

.b-fc {
    background-color: orange;
    display: flex;
    flex-direction: column;
    /*flex-wrap: wrap;*/
    flex-basis:70px;
    flex-grow:1;
}

.b-fc > * {
  flex-grow: 1;
  flex-basis: 100px;
}

.b-fc > *:nth-child(1) {
  background-color: red;
}

.b-fc > *:nth-child(2) {
  background-color: blue;
}

.b-fc > *:nth-child(3) {
  background-color: green;
}
Run Code Online (Sandbox Code Playgroud)
<div class="wrapper">
  <div class="a-fc">
   <div>a1</div>
  </div>
  <div class="b-fc">
  <div>b1</div><div>b2</div><div>b3</div>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

FC = 弹性容器。FI = 弹性项目。

.b-fc当原始行上留下的空间低于 70px 时,我可以放置到新行上。

我的任务:b-fc当没有创建新行/它们不换行时,我希望FI 垂直堆叠。我希望b-fcFI 在b-fc换行时水平对齐。


当前解决方案

在上面的代码片段中,我试图通过在“.b-fc”的 FI 上设置“flex-basis”来编写一组适用于这两种情况的属性来完成我的任务。如果 .b-fc 的 FI 剩余空间小于此 flex-basis (100px),则 FI 将垂直堆叠。弱点:i) 如果`.b-fc` 的`width` 大于300px,它的FIs 水平对齐ii) 当`.b-fc` 环绕,当`.bf-c` 小于它的FIs 环绕超过 300 像素。

因此,我认为在.b-fc换行时能够应用 CSS 会更强大。这可能吗?

*想法 1:CSS 变量和 JS*

也许使用 CSS 变量/SASS 我可以不断评估 FC - .a-fc<= 小于 70px。如果为 true,则将样式应用于.b-fc.

想法 2:媒体查询

另一种选择是测试 row2 何时创建,使用媒体查询来捕获它并将 CSS 应用于.b-fc媒体查询。


PS 类似的问题在 2015 年之前曾在这里问过。也许自那以后出现了新技术。

Tem*_*fif 3

对于这种特殊情况,您可以考虑使用与max()结合flex-basis。技巧是要么有0px(水平项目),要么有一个非常大的值(垂直项目)。

您会注意到,这不是通用解决方案,该值基于您的 html 结构:

395px = 300px (width of a-fx) + 70px (flex-basis of b-fc) + 10px (border of wrapper) + 16px (default body margin) - 1px
Run Code Online (Sandbox Code Playgroud)

395px = 300px (width of a-fx) + 70px (flex-basis of b-fc) + 10px (border of wrapper) + 16px (default body margin) - 1px
Run Code Online (Sandbox Code Playgroud)
.wrapper {
  border: 5px solid pink;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.a-fc {
  background-color: purple;
  width: 300px;
}

.b-fc {
  background-color: orange;
  display: flex;
  flex-wrap: wrap;
  flex-basis: 70px;
  flex-grow: 1;
}

.b-fc>* {
  flex-grow: 1;
  flex-basis: max(0px, (100vw - 395px)*100);
  height: 100px;
}

.b-fc>*:nth-child(1) {
  background-color: red;
}

.b-fc>*:nth-child(2) {
  background-color: blue;
}

.b-fc>*:nth-child(3) {
  background-color: green;
}
Run Code Online (Sandbox Code Playgroud)

所以回答你的问题:不,我们不能在包装上应用CSS(CSS无法检测包装),但我们总能找到每种情况的解决方法。

类似问题:

没有媒体查询如何实现 3 列桌面到 1 列移动布局

CSS网格没有媒体查询的最大列数