当 flex-direction 为“column”时,CSS flex-basis 不起作用

问题描述 投票:0回答:5

我的目标是使用 Flexbox 创建一个两列布局,其中第一列有两行,第二列有一行,如下所示:

enter image description here

在第三个项目上设置

flex-basis: 100%
可以达到所需的效果,但前提是容器的
flex-direction
row

enter image description here

flex-direction
更改为
column
会产生以下结果,除非显式设置
height
,这在我的项目中是不可行的:

enter image description here

如何在不显式设置容器的

height
的情况下获取第一张图像?

这是一个说明问题的 Plunker

body {
  display: flex;
  height: 100px;
  width: 100px;
}
.container {
  display: flex;
  flex-direction: column; /* Setting this to `row` gives the expected effect,but rotated */
  flex-grow: 1;
  flex-wrap: wrap;
  /* height: 100%; */ /* Setting this fixes the problem, but is infeasible for my project*/
}
.item {
  flex-grow: 1;
}
.one {
  background-color: red;
}
.two {
  background-color: blue;
}
.three {
  background-color: green;
  flex-basis: 100%;
}
<div class="container">
  <div class="item one">&nbsp;</div>
  <div class="item two">&nbsp;</div>
  <div class="item three">&nbsp;</div>
</div>

html css flexbox
5个回答
23
投票

为什么不起作用

仅当 Flex 项目的“初始主尺寸”溢出 Flex 容器时,才会发生

Flex 换行。在 flex-direction: row 的情况下,这是当它们的弹性项目比容器宽时。使用

flex-direction: column
,它们必须溢出容器的高度。

但在 CSS 中,高度的行为与宽度根本不同。 CSS 中容器的高度由其子级的高度决定。因此,如果没有“某物”限制容器的高度,它们弯曲的项目永远不会溢出;他们只是让容器更高。如果它们不溢出,它们就不会包裹。

可能的解决方案

你必须限制容器的高度。最明显的方法(你说的不可能)是设置一个显式的 height

max-height


问问自己为什么需要限制高度。是留在视口内吗?您可以使用
viewport-relative
单位并设置类似

max-height: 100vh

的内容。它是否等于该弹性容器外部另一列的高度?您也许可以使用另一个弹性盒来约束它。使这个弹性容器成为外部弹性盒中的弹性项目。不过,外部弹性盒中的其他东西必须确定其高度。

在改变方向时(

flex: none

2
投票
@media


我在 Chrome 和 Firefox 中测试了它。
    

据我了解,以下代码给出了您想要的结果:


0
投票

除了

flex-basis:50%;
 之外,此代码与您在 plunker 中使用的代码相同。由于某种原因,plunker 不支持 
flex-basis

,另请参阅:



    

enter image description here我认为您应该使用网格系统来构建布局。在你的第一张图片上,我们可以看到 2 列:第一列是红色和蓝色框,第二列是绿色框。


0
投票

<div class="flex-container"> <div class="col column"> <div class="content red"></div> <div class="content blue"></div> </div> <div class="col"> <div class="content green"></div> </div> </div>

使用这些样式:

.flex-container {
   display:flex;
}
.col {
   flex:1;
   display:flex;
}
.column {
   flex-direction:column;
}
.content {
   flex:1;
}

这是使用您的演示目标的快速代码:

https://jsfiddle.net/wyyLvymL/
希望能帮助到你! (如果您需要了解它是如何工作的,请联系我)

这个工作正常,使用一点技巧


0
投票

https://jsfiddle.net/Lu79r2kb/

    

© www.soinside.com 2019 - 2024. All rights reserved.