首页 > 解决方案 > 当它换行到新行时,我可以将 CSS 应用于 flex-item 吗?

问题描述

.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;
}
<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>

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

.b-fc当原始行上存在的空间低于 70 像素时,我可以将其放置到新行上。

我的任务:我希望b-fcFI 在没有创建新行/不换行时垂直堆叠。我希望FI 在换b-fc行时水平对齐。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。如果为真,则将样式应用于.b-fc.

想法 2:媒体查询

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


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

标签: javascripthtmlcssflexbox

解决方案


对于这种特殊情况,您可以考虑使用max()combine with 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

.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;
}
<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>

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

类似的问题:

无媒体查询如何实现3列桌面转1列移动布局

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


推荐阅读