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

标签 javascript html 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;
}
<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 = flex 容器。
FI = flex 元素。
我可以放置 .b-fc当保留在原始行上的空间低于 70 像素时,移到新行上。
我的任务:我要b-fc的 FI 在没有创建新行/不换行时垂直堆叠。我要b-fc的 FI 在 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 <= 大于 70 像素。如果为真,将样式应用于 .b-fc .

想法2:媒体查询
另一种选择是测试何时生成第 2 行,使用媒体查询来捕获它并将 CSS 应用于 .b-fc与媒体查询。

附:有人问过类似的问题 here之前在 2015 年。也许从那以后出现了新技术。

最佳答案

对于这种特殊情况,您可以考虑使用 max()结合 flex-basis .诀窍是要么拥有0px (水平元素)或非常大的值(value)(垂直元素)。
您会注意到这不是通用解决方案,其值取决于您的 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 无法检测包装),但我们总能找到每种情况的解决方法。
类似的问题:
Without media queries how to achieve 3 column desktop to 1 column mobile layout
CSS grid maximum number of columns without media queries

关于javascript - 当它换行到新行时,我可以将 CSS 应用于 flex-item 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65634843/

相关文章:

css "opacity"属性不支持

javascript - 计算并显示页面加载进度百分比

javascript - Promise 解析时 JSON 输入意外结束

javascript - 将参数传递到 iframe src

JavascriptCore 不从类中导出方法

html - 将 CSS 与 HTML 连接的问题

jquery - 如何在父td宽度内设置图像大小?

html - react redux 中 api 调用的 400 错误在示例中正常工作

javascript - AngularJS - 如何对操作 HTML 的指令进行单元测试?

javascript - Node - 多个 json 文件到 API